Silverlight:INotifyPropertyChanged似乎不起作用

时间:2009-11-20 00:45:15

标签: silverlight

我暂时没有实现这种模式(当我这样做的时候是2,而不是3),我有几个看起来都很简单的例子,但是我无法解决我的问题。在下面的代码中做错了(当属性事件触发时,Items不会更新):

public partial class Index : Page
{
    private IndexViewModel _vm;

    public Index()
    {
        InitializeComponent();
        _vm = new IndexViewModel(19);           

        this.TheDataGrid.ItemsSource = _vm.Rows;
    }




public class IndexViewModel : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) 
        {          
            this.PropertyChanged(this, e); 
        }

public SortableCollectionView Rows 
        { 
            get
        {
            return _rows;
        }
        set
        {
            if (_rows == value) 
                return;

            _rows = value;
            this.OnPropertyChanged(new  PropertyChangedEventArgs("Rows"));                                
        }
    }

这不刷新我的数据网格...作为'hack'我必须将datagrid对象传递给我的viewmodel并将其绑定到那里:

public IndexViewModel(int containerModelId, DataGrid shouldNotNeed)
        {
            ContainerModelId = containerModelId;

        LoadOperation<vwColumn> headings = _ttasContext.Load(_ttasContext.GetRecordColumnsQuery(ContainerModelId));
        headings.Completed += (sender2, e2) =>
        {
            //load data
            LoadOperation<vwDataValue> data = _ttasContext.Load(_ttasContext.GetRecordsQuery(ContainerModelId, null));
            data.Completed += (sender3, e3) =>
            {

                    Rows = FormatData(data, headings);
shouldNotNeed.ItemsSource = Rows;
                };
            };
        }

3 个答案:

答案 0 :(得分:2)

将_vm.Rows分配给TheDataGrid.ItemsSource不会自动连接任何更改通知回调。试试这个: 在xaml:

<... x:Name=TheDataGrid ItemsSource={Binding Rows}>

在代码中:

this.DataContext = _vm;

答案 1 :(得分:0)

正如Codism指出你的主要问题是你需要使用绑定来利用INotifyPropertyChanged。但是我会推荐这种实现模式: -

public event PropertyChangedEventHandler PropertyChanged;

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

...

  set 
  {
     if (_rows != value)
     {
        _rows = value;
        NotifyPropertyChanged("Rows");
     }
  }

请注意,此方法可以最大限度地减少对未观察其属性的对象实例的影响。在原始模式中,您创建PropertyChangedEventArgs的实例,并调用事件委托,无论是否有任何实际监听。

答案 2 :(得分:0)

  

this.TheDataGrid.ItemsSource = _vm.Rows

当一个集合被指定为DataGird的ItemsSource时,如果源实现了INotifyCollectionChanged,DataGrid可以观察到对集合所做的任何更改。
从您的代码示例中,我无法判断SortableCollectionView类型是实现INotifyCollectionChanged还是继承自ObservableCollection。 实现INotifyCollectionChanged意味着您无法重置属性行的支持字段_rows,您可以清除集合中的项目并根据需要添加它们。
希望这有帮助