2011-03-23 28 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,你會發現它工作正常。