好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C# TextBox数据绑定的方法

经常写用一个TextBox显示某个对象,然后编辑之后再保存的程序。以前都是在TextBox_TextChanged事件中修改对象的值,或者保存的时候再读取TextBox.Text属性保存对象的值。这样比较麻烦,而且经常容易出错。后来了解了C#的数据绑定,发现能够很好的解决这个问题。

1. 首先C#的TextBox本身就带数据绑定功能。

下面的代码就是把_myData对象的"TheValue"属性绑定到textBox1和textBox2的"Text"属性。最后一个参数不同:

1)其中DataSourceUpdateMode.OnPropertyChanged表示textBox1.Text发生变化,_myData.TheValue也变化,叫双向绑定。

2)DataSourceUpdateMode.Never表示Text1.Text变化不影响_myData.TheValue的值,是单向绑定。

?

private void Form1_Load( object sender, EventArgs e)

{

   _myData = new MyData();

   textBox1.DataBindings.Add( "Text" , _myData, "TheValue" , false , DataSourceUpdateMode.OnPropertyChanged);

   textBox2.DataBindings.Add( "Text" , _myData, "TheValue" , false , DataSourceUpdateMode.Never);

}

2.也许有人留意到了,为什么上面的叫"双向绑定"呢?如果_myData.TheValue的值变化了,两个文本框的Text会变化吗?不错,仅在 textBox上数据绑定还不叫双向绑定,对象数据变化要通知绑定该对象的控件才行。这样就需要对象实现INotifyPropertyChanged接 口。

?

public class MyData : INotifyPropertyChanged

{

   private string _theValue = string .Empty;

 

   public string TheValue

   {

     get { return _theValue; }

     set

     {

       if ( string .IsNullOrEmpty(value) && value == _theValue)

         return ;

 

       _theValue = value;

       NotifyPropertyChanged(() => TheValue);

     }

   }

 

   public event PropertyChangedEventHandler PropertyChanged;

 

   public void NotifyPropertyChanged<T>(Expression<Func<T>> property)

   {

     if (PropertyChanged == null )

       return ;

 

     var memberExpression = property.Body as MemberExpression;

     if (memberExpression == null )

       return ;

 

     PropertyChanged.Invoke( this , new PropertyChangedEventArgs(memberExpression.Member.Name));

   }

}

3.好了,数据绑定完成了,看看效果吧。textBox1.Text变化—>_myData.TheValue变化—>textBox2.Text变化。反过来textBox2.Text变化就不是这样了,因为textBox2使用的单向绑定。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://HdhCmsTestcnblogs测试数据/zhaoshujie/p/9678899.html

dy("nrwz");

查看更多关于C# TextBox数据绑定的方法的详细内容...

  阅读:47次