0

I tried to bind a property to a nested object, but it fails.

I have taken a look at those questions, but i think i made another mistake somewhere else. Maybe someone can give i hind.

WPF: How to bind to a nested property?

binding to a property of an object

To upper slider/textbox has a correct binding while the lower one fails to do so.

I have two sliders with corrosponding textboxes:

<StackPanel>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
    <TextBox Text="{Binding Path= boundnumber, Mode=TwoWay, FallbackValue='binding failed'}" ></TextBox>
    <Slider Value="{Binding Path= boundnumber, Mode=TwoWay}" Width="500" Maximum="1000" ></Slider>
</StackPanel>

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" DataContext="{Binding Path=myDatarow}">

        <TextBox Text="{Binding Path= boundnumber, Mode=TwoWay, FallbackValue='binding failed'}" ></TextBox>
        <Slider Value="{Binding Path= boundnumber, Mode=TwoWay}" Width="500" Maximum="1000" ></Slider>
</StackPanel>
</StackPanel>

Code behind:

public partial class MainWindow : INotifyPropertyChanged
    {
        public MainWindow()
        {
            DataContext = this;
            InitializeComponent();
        }

        private int _boundnumber;
        public int boundnumber
        {
            get { return _boundnumber; }
            set
            {
                if (value != _boundnumber)
                {
                    _boundnumber = value;
                    OnPropertyChanged();
                }
            }
        }

        Datarow myDatarow = new Datarow(11);

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string propertyname = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
        }
    }

class Datarow : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyname = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
    }

    public Datarow()
    {

    }

    public Datarow(int number)
    {
        boundnumber = number;
    }

    private int _boundnumber;
    public int boundnumber
    {
        get { return _boundnumber; }
        set
        {
            if (value != _boundnumber)
            {
                _boundnumber = value;
                OnPropertyChanged();
            }
        }
    }
}
Community
  • 1
  • 1
Raros
  • 21
  • 1
  • 1
  • 7

1 Answers1

0

You need to expose your myDatarow into a public property like your boundnumber.

    private DataRow _myDatarow = new DataRow(11);
    public DataRow myDataRow
    {
        get { return _myDatarow; }
    }

And just an additional advice. It's better to separate your DataContext class from the MainWindow.

janonimus
  • 1,911
  • 2
  • 11
  • 11