1

我有以下内容:

   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 是否已更改。我对自定义事件知之甚少,但我无法弄清楚这一点,互联网上的事件也不知道。

IF changedText 更改,然后将另一个文本框设置为该字符串。

4

1 回答 1

5

用属性替换您的字段,并检查设置器中的值是否更改。如果它发生变化,请引发一个事件。有一个用于属性更改通知的接口,称为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";
于 2013-01-29T12:13:41.813 回答