我有以下内容:
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FarmKeeper.Forms
{
public partial class FarmLogs : Form
{
static string errorLogText = "";
public string changedText = "";
public FarmLogs()
{
InitializeComponent();
string txtLoginLogPath = @"../../Data/LoginLog.txt";
StreamReader readLogins = new StreamReader(txtLoginLogPath);
txtLoginLog.Text = readLogins.ReadToEnd();
readLogins.Close();
loadLogs();
changedText = errorLogText;
txtErrorLog.Text = changedText;
}
public static void loadLogs()
{
string txtErrorLogPath = @"../../Data/MainErrorLog.txt";
StreamReader readErrors = new StreamReader(txtErrorLogPath);
errorLogText = readErrors.ReadToEnd();
readErrors.Close();
}
}
}
现在,我要做的是检查字符串 changedText 是否已更改。 我对自定义事件了解一点,但我就是想不通,互联网上的也不是。
如果 changedText 改变了,则将另一个文本框设置为该字符串。
最佳答案
用属性替换您的字段,并检查 setter 中的值是否发生变化。如果它发生变化,则引发一个事件。有一个名为 INotifyPropertyChanged
的属性更改通知界面:
public class Test : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string myProperty;
public string MyProperty
{
get
{
return this.myProperty;
}
set
{
if (value != this.myProperty)
{
this.myProperty = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("MyProperty"));
}
}
}
}
}
只需将处理程序附加到 PropertyChanged
事件:
var test = new Test();
test.PropertyChanged += (sender, e) =>
{
// Put anything you want here, for example change your
// textbox content
Console.WriteLine("Property {0} changed", e.PropertyName);
};
// Changes the property value
test.MyProperty = "test";
关于c# - 为字符串 c# 创建自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14582536/