0

在我的程序中,我DataGrid通过 MVVM 实现了一个。旁边DataGrid是一个按钮,它执行我命名为“Fill Down”的命令。它采用其中一列并将字符串复制到该列中的每个单元格。问题是视图不会进行更改,直到我更改页面然后返回到带有DataGrid. 为什么会发生这种情况,我能做些什么来解决它?

xml:

<Button Command="{Binding FillDown}" ... />
<DataGrid ItemsSource="{Binding DataModel.Collection}" ... />

视图模型:

private Command _fillDown;

public ViewModel()
{
     _fillDown = new Command(fillDown_Operations);
}

//Command Fill Down
public Command FillDown { get { return _fillDown; } }
private void fillDown_Operations()
{
    for (int i = 0; i < DataModel.NumOfCells; i++)
    {
        DataModel.Collection.ElementAt(i).cell = "string";
    }
    //**I figured that Notifying Property Change would solve my problem...
    NotifyPropertyChange(() => DataModel.Collection);
}

-如果您想查看更多代码,请告诉我。

是的,对不起,我的收藏是ObservableCollection

4

1 回答 1

3

在属性的设置器中调用 NotifyPropertyChanged():

public class DataItem
{
   private string _cell;
   public string cell //Why is your property named like this, anyway?
   {
       get { return _cell; }
       set
       {
           _cell = value;
           NotifyPropertyChange("cell");

           //OR

           NotifyPropertyChange(() => cell); //if you're using strongly typed NotifyPropertyChanged.
       }
   }
}

旁注:

改变这个:

for (int i = 0; i < DataModel.NumOfCells; i++)
{
    DataModel.Collection.ElementAt(i).cell = "string";
}

对此:

foreach (var item in DataModel.Collection)
    item.cell = "string";

这更清洁和可读。

于 2013-10-28T17:59:03.060 回答