为字符串 C# 创建自定义事件

本文关键字:自定义 事件 创建 字符串 | 更新日期: 2023-09-27 17:56:41

>我有以下内容:

   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,是否更改。我对自定义事件有所了解,但我无法弄清楚这一点,互联网上的事件也是如此。

如果更改文本已更改,则将另一个文本框设置为该字符串。

为字符串 C# 创建自定义事件

将字段替换为属性,并检查资源库中的值是否更改。如果它发生变化,请引发事件。有一个名为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";