您的位置:首页 > 移动开发 > Objective-C

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

2012-02-21 16:32 363 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息