将列表绑定到DataGrid Silverlight

时间:2010-03-31 10:44:30

标签: silverlight collections binding

我将List绑定到DataGrid元素时遇到问题。我创建了一个实现INotifyPropertyChange并保留订单列表的类:

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中,有一个简单的DataGrid组件绑定OrderList元素:

<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( “项目”);

DataContext设置为全局对象:

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

问题在于,当我单击按钮时,该项目不会在dataGrid中出现。单击网格行后,它会出现。像INotifyPropertyChange这样的接缝不起作用...... 我做错了什么?

请帮助:)

1 个答案:

答案 0 :(得分: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