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

标签 c#

我有以下内容:

   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/

相关文章:

c# - 当按下按钮时如何从 Collection View 中获取相应的对象?

c# - MongoDb 使用新的异步方法创建存储库模式

c# - 递归 - 二叉树

c# - 当我转换为对象时,null GameObject 变为非空

c# - 使用泛型的 Dapper 方法

c# - 即使定义了其他主键, Entity Framework 6 也会创建 Id 列

c# - 使用通用目的地映射不起作用?

c# - UnmanagedExports 函数参数 - 导致 VBA 49 错误的 DLL 调用约定

c# - 如何从基于 OnMethodBoundaryAspect 的日志记录中排除?

c# - TryUpdateModel 和 System.MissingMethodException