2011-03-23 25 views
2

在我的MainWindow中,我有一个ObservableCollection,它显示在每个绑定的Listbox中。如果使用路径,绑定不会刷新

如果我更新我的集合,修改显示在列表中。

这工作:

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> 

这个版本的作品不是:

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> 

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

回答

5

您需要将您的集合公开为属性,现在它是一个字段。所以,再一次使ARR私人和补充:

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

然后,你将能够绑定像{Binding Path=Arr},假设this是当前的DataContext。

4

您不能绑定到一个字段,只能绑定到一个属性。尝试在一个属性中包装arr,你会发现它工作正常。