【发布时间】:2015-03-30 07:01:15
【问题描述】:
我有一个 WPF View 绑定到实现 INotifyPropertyChanged 的 ViewModel。在那个View 中,我有一个DataGrid,其项目绑定到ViewModel 中的ObservableCollection。 ObservableCollection 成员本身不实现 INotifyPropertyChanged。在 DataGrid 中,我有三列 - 两列可编辑的 DatePicker 列和一个只读的 Checkbox 列,当用户选择包含当前日期的日期范围时,应该检查它们。
绑定在第一次加载视图时起作用,但是当我更改其他两列中的日期时,Checkbox 的绑定没有更新,大概是因为 MyDomainObject 类没有实现 INotifyPropertyChanged。我真的不想在这里实现那个接口,因为ObservableCollection 是从 Web 服务返回的类型,这样做会迫使我创建和维护该类型的副本,而且我有很多类似的场景在我的应用程序中。有什么办法可以强制复选框更新?如果可能的话,我更愿意避免使用后面的代码——如果我必须打破这条规则,我知道该怎么做。
下面的代码应该能大致说明问题:
XAML:
<DataGrid ItemsSource="{Binding MyDomainObjectCollection}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Start Date">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding StartDate, StringFormat=d}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<DatePicker SelectedDate="{Binding StartDate, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="End Date">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding EndDate, StringFormat=d}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<DatePicker SelectedDate="{Binding EndDate, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Is Active">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsActive, Mode=OneWay}" IsEnabled="False" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
查看模型:
public class MyViewModel : INotifyPropertyChanged {
ObservableCollection<MyDomainObject> _myDomainObjectCollection;
public ObservableCollection<MyDomainObject> MyDomainObjectCollection {
get { return this._myDomainObjectCollection; }
set { this._myDomainObjectCollection = value; this.OnPropertyChanged(); }
}
[...]
}
域对象:
public class MyDomainObject {
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool IsActive {
get { return StartDate < DateTime.Now && EndDate > DateTime.Now; }
}
}
【问题讨论】:
标签: c# .net wpf mvvm data-binding