Search code examples
c#wpfdatacontext

Binding class in class property in WPF C# with Datacontext


How to access a property in a class in class property. Value2 is working, Value1 not. If I bind Value1 in codeBehind, Value1 works. The actual code:

class Class1 : INotifyPropertyChanged
{
    private string _Value1;

    public string Value1
    {
        get { return _Value1; }
        set { _Value1 = value; NotifyPropertyChanged("Value1"); }
    }
    [...]
    }

Class2.cs:

class Class2 : INotifyPropertyChanged
    {
        private string _Value2;

        public string Value2
        {
            get { return _Value2; }
            set { _Value2 = value; NotifyPropertyChanged("Value2"); }
        }

        public Class2()
        {
            Class1 class1 = new Class1();
            class1.Value1 = "Value 1 set";
            Value2 = "Value2 set";
        }
    [...]
    }

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    Class2 class2 = new Class2();
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = class2;
    }
}

MainWindow.xaml

<Grid>
    <TextBox Text="{Binding Path=class1.Value1}" /> 
    <TextBox Text="{Binding Path=Value2}" />
</Grid>

Solution

  • The expression

    Class1 class1 = new Class1();
    

    declares a local variable in the Class2 constructor, which has no meaning outside the constructor.

    You probably wanted to have a property of type Class1 in Class2:

    class Class2 : INotifyPropertyChanged
    {
        private Class1 class1;
    
        public Class1 Class1
        {
            get { return class1; }
            set { class1 = value; NotifyPropertyChanged(nameof(Class1)); }
        }
    
        public Class2()
        {
            Class1 = new Class1 { Value1 = "Value 1 set" };
            Value2 = "Value2 set";
        }
    
        ...
    }
    

    Bind to it by

    <TextBox Text="{Binding Path=Class1.Value1}" /> 
    

    Maybe the property doesn't even need to be writeable:

    class Class2 : INotifyPropertyChanged
    {
        public Class1 Class1 { get; } = new Class1();
    
        public Class2()
        {
            Class1.Value1 = "Value 1 set";
            Value2 = "Value2 set";
        }
    
        ...
    }