MTR
MTR

Reputation: 1740

Binding doesn't refresh if path used

In my MainWindow I have an ObservableCollection which is shown in a Listbox per Binding.

If I update my Collection the modification is shown in the list.

This works:

public ObservableCollection<double> arr = new ObservableCollection<double>();

public MainWindow()
{
            arr.Add(1.1);
            arr.Add(2.2);
            testlist.DataContext = arr;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
   arr[0] += 1.0;
}
<ListBox Name="testlist" ItemsSource="{Binding}"></ListBox>

This version works not:

public ObservableCollection<double> arr = new ObservableCollection<double>();

public MainWindow()
{
            arr.Add(1.1);
            arr.Add(2.2);
            testlist.DataContext = this;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
   arr[0] += 1.0;
}
<ListBox Name="testlist" ItemsSource="{Binding Path=arr}"></ListBox>

Can you tell me why? I would like to give this as the DataContext, because there are many other properties to show in my dialog and it would be nice if I wouldn't have to set the DataContext for every individual control.

Upvotes: 2

Views: 164

Answers (2)

CodeNaked
CodeNaked

Reputation: 41403

You need to expose your collection as a property, right now it's a field. So make arr private again and add:

public ObservableCollection<double> Arr {
    get {
        return this.arr;
    }
}

Then you will be able to bind like {Binding Path=Arr}, assuming this is the current DataContext.

Upvotes: 5

Dan Puzey
Dan Puzey

Reputation: 34218

You can't bind to a field, only to a property. Try wrapping arr in a property and you should find it works fine.

Upvotes: 4

Related Questions