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

时间:2013-01-29 12:08:58

标签: 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已更改,则将另一个文本框设置为该字符串。

1 个答案:

答案 0 :(得分: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";