2010-03-31 186 views
1

我有一個綁定列表到DataGrid元素的問題。我創建了一個實現INotifyPropertyChange和保持訂單列表類:綁定列表到DataGrid Silverlight

public class Order : INotifyPropertyChanged 
{ 

    private String customerName; 

    public String CustomerName 
    { 
     get { return customerName; } 
     set { 
       customerName = value; 
       NotifyPropertyChanged("CustomerName"); 
      } 
    } 

    private List<String> orderList = new List<string>(); 

    public List<String> OrderList 
    { 
     get { return orderList; } 
     set { 
       orderList = value; 
       NotifyPropertyChanged("OrderList"); 
      } 
    } 




    public void NotifyPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

在XAML中有綁定的OrderList元素的簡單DataGrid組件:

<data:DataGrid x:Name="OrderList" ItemsSource="{**Binding OrderList**, Mode=TwoWay}" Height="500" Width="250" Margin="0,0,0,0" VerticalAlignment="Center" 

我也有在GUI中的按鈕taht向OrderList添加元素:

order.OrderList.Add(「item」);

的DataContext設置爲全局對象:

 Order order = new Order(); 
     OrderList.DataContext = order; 

的問題是,當我點擊該按鈕,該項目不DataGrid中apear。它在點擊網格行後顯示。它接縫像INotifyPropertyChange不起作用... 我在做什麼錯?

請幫助:)

回答

2

INotifyPropertyChange工作正常,因爲你的代碼到一個新的項目添加到現有的List實際上並沒有新的價值進行重新分配給OrderList屬性(也就是set例程是永遠稱爲)沒有致電NotifyPropertyChanged。嘗試這樣的: -

public class Order : INotifyPropertyChanged 
{ 

    private String customerName; 

    public String CustomerName 
    { 
     get { return customerName; } 
     set { 
       customerName = value; 
       NotifyPropertyChanged("CustomerName"); 
      } 
    } 

    private ObservableCollection<String> orderList = new ObservableCollection<String>(); 

    public ObservableCollection<String> OrderList 
    { 
     get { return orderList; } 

    } 


    public void NotifyPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

ObservableCollection<T>類型支持通知INotifyCollectionChanged將通知DataGrid當項目添加到或者從集合中刪除。

+0

非常感謝。這很好:) – Rafal 2010-03-31 13:14:13