WPF - 绑定到另一个对象内的自定义对象的属性 [英] WPF - binding to a property of a custom object that is inside another object
问题描述
我在WPF / C#的工作。我有两个自定义类:
I'm working in WPF 4 / C#. I have two custom classes:
public class c1 {
public string prop1 { get; set; }
public c1() {
prop1 = "world";
}
}
public class c2 {
public string prop1 { get; set; }
public c1 obj1 = new c1();
public c2() {
prop1 = "hello";
}
}
从内XAML,我要绑定到这些类的属性。以下是我有:
From within XAML, I want to bind to properties of these classes. Here is what I have:
<Window.Resources>
<my:c2 x:Key="c2"/>
</Window.Resources>
<StackPanel>
<TextBlock DataContext="{DynamicResource c2}" Text="{Binding prop1}"/>
<TextBlock DataContext="{DynamicResource c2}" Text="{Binding obj1.prop1}"/>
</StackPanel>
(这里的&LT;我:C2 ../& GT;
实例化C2类。)第一个TextBlock的结合的作品。第二不。为什么我不能绑定到该OBJ1的属性?我只似乎能够绑定到即时类的属性。我希望能够绑定到其他的东西像属于即时类或子类的属性,如上图所示数组中的元素。我在想什么?如果我包裹obj1.prop1使用的get / set立即类的另一个属性,它的工作原理。但我不希望有这样做,特别是当我开始使用数组,我不希望每个元素包装成一个单独的属性!
(Here the <my:c2 ../>
instantiates the c2 class.) The first TextBlock binding works. The second does not. Why can't I bind to a property on the obj1? I only seem to be able to bind to properties of the immediate class. I want to be able to bind to other stuff like an element in an array that belongs to the immediate class or a property of a child class, as shown above. What am I missing? If I wrap the obj1.prop1 in another property of the immediate class using get/set, it works. But I don't want to have to do that, particularly if I start using arrays, I don't want to wrap each element into a separate property!
推荐答案
您 OBJ1
是一个领域,不是一个属性,因此,你不能访问C1对象。
Your obj1
is a field, not a property, therefore you can't access the C1 object.
考虑这个:
public class c2 {
public string prop1 { get; set; }
private readonly c1 _obj1;
public c2() {
prop1 = "hello";
_obj1 = new c1();
}
public c1 PropObj1 { get { return _obj1; } }
}
和
<TextBlock DataContext="{DynamicResource c2}" Text="{Binding PropObj1.prop1}"/>
PS。下一次,最好使用标准的命名规则(例如小写场/变量,大写的属性等)为例,让人们看到了问题,越快!
PS. Next time better to use an example with standard naming conventions (e.g. lower case fields/variables, upper case properties etc) to allow people to see the problem sooner!
这篇关于WPF - 绑定到另一个对象内的自定义对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!