如何对设计时winform自定义控件的属性更改做出反应

时间:2010-12-03 16:07:51

标签: c# winforms

我找不到关于如何做到的anu doc或教程?

1 个答案:

答案 0 :(得分:0)

试试这个 - 我添加了一个事件并在属性的set方法中触发它。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CustomControl
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        //add a handle to the property changed event
        myButton1.OnNameChanged += new EventHandler(myButton1_OnNameChanged);
    }

    void myButton1_OnNameChanged(object sender, EventArgs e)
    {
        MessageBox.Show("My Name Changed");
    }
}


public class myButton : Button
{
    private string _Name = "";
    public event EventHandler OnNameChanged;
    public string myName
    {
        get { return _Name; }
        set
        {
            _Name = value;
            if (OnNameChanged != null)
                OnNameChanged(this,EventArgs.Empty);

            //just for Demonstrative purposes I added this so you could see the _Name actually change
            this.Text = _Name;
        }
    }

    //added this to demonstrate the name changing 
    protected override void OnClick(EventArgs e)
    {
        base.OnClick(e);
        myName = "my New Name";
    }
}
}

编辑: 对不起,如果我误解了这个问题。我刚注意到你在设计时说过。我以为你的意思是通过在事件属性部分双击它来添加事件。这段代码允许这样做,虽然我不确定这是你的意思。请澄清,也许我仍然可以提供帮助。