1

(我是 WPF 新手)我有几个属性的对象,我想绑定到文本框。我有一个名为 txtStudentName 的文本框控件。寻找一些例子让我觉得我需要使用下一个方法:

$txtStudentName.DataBindings.Add(,,);

但是我的文本框对象中没有 DataBindings 属性。

任何人?

4

3 回答 3

2

如果要绑定的对象是公共的并且是数据上下文中对象的属性,则还可以在 XAML 中进行绑定:

<Window x:Class="CarSystem.AlarmsDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        DataContext="{Binding MyDataContextObject, RelativeSource={RelativeSource Self}}"
        Title="LPR - Mobile Plate Hunter 900: Alarms">

    <Grid>
        <TextBox Text={Binding Path=MyTextProperty, Mode=TwoWay} />
    </Grid>
</Window>
于 2013-09-06T13:21:50.000 回答
0

像这样绑定:

TextBox MyText = new TextBox();

Binding binding = new Binding();
binding.Path = new PropertyPath("Name"); //Name of the property in Datacontext
BindingOperations.SetBinding(MyText,TextBox.TextProperty , binding);

如果要绑定到包含 Name 属性的某个对象,则还必须将 binding.Source 设置为该对象。

于 2013-09-06T13:13:21.757 回答
0

由于您标记了 WPF,因此请考虑仅在 XAML 中执行此操作:

<TextBox Text="{Binding Path=SomeTextProperty, Mode=TwoWay}" />
于 2013-09-06T13:15:35.060 回答