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.
You need to expose your collection as a property, right now it’s a field. So make arr private again and add:
Then you will be able to bind like
{Binding Path=Arr}, assumingthisis the current DataContext.