如果使用路径,则不会刷新绑定

MTR*_*MTR 2 .net c# wpf xaml binding

在我的MainWindow中,我有一个ObservableCollection,它显示在每个Binding的Listbox中.

如果我更新我的Collection,修改将显示在列表中.

这有效:

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>
Run Code Online (Sandbox Code Playgroud)

这个版本不起作用:

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>
Run Code Online (Sandbox Code Playgroud)

你能告诉我为什么吗?我想把作为DataContext给出,因为在我的对话框中还有很多其他属性要显示,如果我不必为每个单独的控件设置DataContext,那将是很好的.

Cod*_*ked 5

您需要将您的集合公开为属性,现在它是一个字段.所以再次将arr设为私有并添加:

public ObservableCollection<double> Arr {
    get {
        return this.arr;
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你将能够绑定{Binding Path=Arr},假设this是当前的DataContext.