WPF数据按对象名称将对象属性绑定到文本框?

时间:2019-04-19 22:43:09

标签: c# wpf binding

晚上好

我有一个简单的问题:

我知道我可以像这样在数据上下文中绑定对象:

//Class CustomObject with a Property named "Property" with value "obj1"
CustomObject obj1 = new CustomObject("obj1");
DataContext = obj1;
<TextBox Text="{Binding Property}" 

这有效。但是,当我拥有一个以上的物体时,该怎么办? 类。我尝试过这样的事情:

<TextBox Text="{Binding obj1.Property}" 

不幸的是,它不起作用。知道我怎么能 通过对象名称绑定?

谢谢。

编辑: 在C#中,它使用以下代码:

CustomObject obj1 = new CustomObject("Test");
Binding myBinding = new Binding();
myBinding.Path = new PropertyPath("Property");
myBinding.Source = obj1;
textBox1.SetBinding(TextBox.TextProperty, myBinding);

所以我在XAML中尝试了同样的方法,不幸的是没有成功:

 <TextBox Text="{Binding Property, Source=Obj1}"/>

2 个答案:

答案 0 :(得分:0)

尝试一下:

<TextBox DataContext="{Binding Path=Obj1, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" Text="{Binding Property}"/>

在此示例中,Obj1将是您正在编程的任何窗口的属性。 如果您打算将Obj2绑定到同一窗口中的另一个文本框,则将其作为属性,依此类推...

答案 1 :(得分:0)

您将创建一个视图模型类,以将CustomObject实例作为其属性之一保存。

public class MyViewModel
{
    public CustomObject Obj1 { get; set } 
    // declare other properties ...
}

然后将视图模型的实例分配给窗口的DataContext

var obj1 = new CustomObject("obj1");
var vm = new MyViewModel
{
    Obj1 = obj1
    // assign other properties ...
};
DataContext = vm;

现在像这样绑定它:

<TextBox Text="{Binding Obj1.Property}" />