WPF - binding to a property of a custom object that is inside another object

前端 未结 2 1519
北海茫月
北海茫月 2021-02-08 18:55

I\'m working in WPF 4 / C#. I have two custom classes:

public class c1 {
    public string prop1 { get; set; }

    public c1() {
        prop1 = \"world\";
             


        
相关标签:
2条回答
  • 2021-02-08 19:04

    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!

    0 讨论(0)
  • 2021-02-08 19:21

    You can't bind to fields, they have to be properties.

    0 讨论(0)
提交回复
热议问题