【问题标题】:Binding List to DataGrid Silverlight将列表绑定到 DataGrid Silverlight
【发布时间】:2010-03-31 10:44:29
【问题描述】:

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

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

我在 GUI 中也有一个按钮,用于向 OrderList 添加一个元素:

order.OrderList.Add("item");

DataContext 设置为全局对象:

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

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

请帮忙:)

【问题讨论】:

    标签: silverlight collections binding


    【解决方案1】:

    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&lt;T&gt; 类型支持通知INotifyCollectionChanged,当项目被添加到集合中或从集合中删除时,它将通知DataGrid

    【讨论】:

      猜你喜欢
      • 2015-01-16
      • 2012-04-02
      • 2013-08-06
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      相关资源
      最近更新 更多