我想在一个层次结构中显示一个房子及其房间,我想说明房子里的房间是否有错误:
class HouseViewModel : INotifyPropertyChanged
{
ObservableCollection<RoomViewModel> rooms = new ObservableCollection<RoomViewModel>();
IReadOnlyCollection<RoomViewModel> Rooms {get; private set;} // assume this raises PropertyChanged correctly
ICommand AddRoomCommand {get; private set;} // assume this adds a RoomViewModel to rooms
}
class RoomViewModel : INotifyPropertyChanged
{
public bool HasError {get; private set;} // assume this raises PropertyChanged correctly
}
<ItemsControl ItemsSource={Binding Houses}> // assume Houses is a collection of HouseViewModel
<ItemsControl.ItemTemplate>
<DataTemplate DataType=HouseViewModel>
<TextBlock Text="Any room has error?" />
<TextBlock Name="NeedHelpHereTextBlock" Text=????? /> // here's where I need help -- this should say True if any Room has an error
<ItemsControl ItemsSource={Binding Rooms}>
<ItemsControl.ItemTemplate>
<DataTemplate DataType=Room>
<TextBlock Text="Has error?" />
<TextBlock Text={Binding HasError} />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
当任何会议室出错时,如何将NeedHelpHereTextBlock的文本设置为True?
我的第一个想法是将一个AnyRoomHasError属性添加到HouseViewModel,将Text绑定到该属性,向ObservableCollection的CollectionChanged事件注册一个事件处理程序并订阅新项目&#39; PropertyChanged事件,如果PropertyChanged事件是针对HasError属性,则更新AnyRoomHasError。
有更好的方法吗?
另请注意,客房可以在后台获取错误。即Room.HasError可能随时更改,无需用户输入。
答案 0 :(得分:0)
对我来说最简单的方法是实现SelectedRoom属性,每次更改此选定值时,父视图模型将扫描其详细信息以查询错误。无需进行事件接线,几乎总是需要对用户选择做一些事情,因此可能已经实现了SelectedRoom。
class HouseViewModel : INotifyPropertyChanged
{
private RoomViewModel _selectedRoom = null;
public RoomViewModel SelectedRoom
{
get { return _selectedRoom ; }
set {
if (_selectedRoom != null)
NotifyPropertyChange("AnyRoomHasError");
if (_selectedRoom != null)
_selectedRoom = value;
}
}
public bool AnyRoomHasError {
get {
return rooms.Any(room => room.HasError);
}
}
}