2010-03-31 133 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