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;开发者_如何学JAVA set; }
public c1 obj1 = new c1();
public c2() {
prop1 = "hello";
}
}
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>
(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!
Your obj1
is a field, not a property, therefore you can't access the C1 object.
Consider this instead:
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; } }
}
And
<TextBlock DataContext="{DynamicResource c2}" Text="{Binding PropObj1.prop1}"/>
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!
You can't bind to fields, they have to be properties.
精彩评论