How can I create a data binding in code using WPF?

When creating UI elements in code it is often necessary to programmatically bind them to data. Fortunately this is relatively straightforward as the following code-snippet using the Binding object from the System.Windows.Data namespace shows:

C# Source (WPF Beta 2)
TextBox nameTextBox = new TextBox();
Binding nameTextBinding = new Binding("Name");
nameTextBinding.Source = person;
nameTextBox.SetBinding(TextBox.TextProperty, nameTextBinding);
// set style on text box, add text box to container etc

This sample assumes you have a type called Person, and an instance called person created elsewhere. Person has a public property called name. First we create our text box (called nameTextBox) and a Binding object, setting the path string for the binding in the constructor. Then we set the data source to the person instance. Alternatively the nameTextBox could get its data through its DataContext or the DataContext of one of its ancestors. If this was the case setting the Source property on the binding would not be necessary.

Next we call the SetBinding() method on the nameTextBox instance, specifying a DependencyProperty and the binding we just created. The example above binds the TextProperty DependencyProperty of nameTextBox to the Name property of the person. In this case the DependencyProperty is a member of the TextBox itself, but it doesn't have to be. For example we can also bind attached properties that might pertain to the container the nameTextBox is placed in.

This example below binds (rather pointlessly) the TopProperty DependencyProperty of the Canvas to the current number of minutes that have elapsed in the current hour for a newly created textbox instance. If the textbox is then added to a canvas (the example assumes a canvas called mainCanvas) the binding will take effect, controlling the top of the textbox in the canvas.

C# Source (WPF Beta 2)
TextBox positionedTextBox = new TextBox();
Binding positionBinding = new Binding("Minute");
positionBinding.Source = System.DateTime.Now;
positionedTextBox.SetBinding(Canvas.TopProperty, positionBinding);
mainCanvas.Children.Add(positionedTextBox);

 

The article comes from http://learnwpf.com/post/2006/06/12/How-can-I-create-a-data-binding-in-code-using-WPF.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值