c#中的变量和文本框映射,不使用文本框更改事件

时间:2017-02-06 12:04:00

标签: c#

我正在尝试更改TextBox值的代码,当与其映射的变量相应更改时,不使用TextBox更改的事件。我没有找到任何线索从哪里开始请帮助我。

以下是代码:

public void varChange(TextBox text)
{
    String name;
    name="sachin";
    text.Text = name;
    MessageBox.Show("" + text.Text);  
}

2 个答案:

答案 0 :(得分:0)

你可以"延伸" TextBox

public class MeTextBox : TextBox
{
    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            //base.Text = value; // use it or not .. whatever
            MyTextWasChanged();
        }
    }

    void MyTextWasChanged()
    {
        String name;
        name="sachin";
        //text.Text = name;
        base.Text = name;
        MessageBox.Show("" + text.Text);  
    }
}

如果这不是您正在寻找的内容,请提供更多详细信息,我会更新此答案。

答案 1 :(得分:0)

您可以使用BindingSource

public partial class Form1 : Form
    {
        private System.Windows.Forms.BindingSource form1BindingSource;

        public string BindedProp { get; set; } //Variable or property binded with TextBox
        public Form1()
        {
            InitializeComponent();
            this.form1BindingSource = new System.Windows.Forms.BindingSource(new System.ComponentModel.Container());
            this.form1BindingSource.DataSource = typeof(binding.Form1);
            this.textBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.form1BindingSource, "BindedProp", true));
            this.form1BindingSource.DataSource = this;
        }      
        //add a button control to assing value code event click
        private void btAssingValueProperty_Click(object sender, EventArgs e)
        {
            BindedProp = "Value assigned";
            form1BindingSource.ResetBindings(false);

        }
        //add a other button control to show value code event click
        private void btShowValueProperty_Click(object sender, EventArgs e)
        {
            MessageBox.Show(BindedProp);
        }

    }
相关问题