在我的程序中,我通过MVVM实现了DataGrid
。此DataGrid
旁边是一个按钮,用于执行我命名为“Fill Down”的命令。它需要其中一列并将字符串复制到该列中的每个单元格。问题是,在我更改页面然后返回到DataGrid
页面之前,视图不会进行更改。为什么会发生这种情况,我该怎么做才能解决它?
XAML:
<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
答案 0 :(得分:3)
在属性的setter中调用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";
更干净,更易读。