在ViewModel中设置SelectedItem
后,如何才能使ListBox
的SelectedItem
高亮显示?从ViewModel更改列表框的SelectedItem
的ItemsSource
势必Bar
的ObservableCollection
(集合是一类Foo
的成员。A按钮被绑定到,增加了一个新的空Bar
实例的集合,然后也设置SelectedItem
到新的空的命令实例。
将该实例添加到集合后,ListBox
被更新以显示新的空白Bar
。但是,设置在视图模型的SelectedItem
财产之后,新的实例未在ListBox
突出,但它被设置并提出PropertyChanged
事件(SelectedItem
显示在视图的其他地方)。
其他详情:
INotifyPropertyChanged
在碱ViewModel类实现,并且在Foo
和Bar
类也实现。
的ListBox
包含自定义ItemTemplate
显示Bar
成员,并且修改该Background
为IsMouseOver
触发定制ItemContainerStyle
。
简化XAML:
<ListBox ItemsSource="{Binding Path=MyFoo.BarCollection}"
SelectedItem="{Binding Path=SelectedItem,
UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<Button Content="Add New Bar"
Command="{Binding Path=AddBarCommand}"/>
简化视图模型:
private Foo _myFoo;
public Foo MyFoo
{
get { return _myFoo; }
set { _myFoo= value; OnPropertyChanged("MyFoo"); }
}
private Bar _selectedItem;
public Bar SelectedItem
{
get { return _selectedItem; }
set { _selectedItem = value; OnPropertyChanged("SelectedItem"); }
}
private void AddBar()
{
Bar newBar = new Bar();
MyFoo.BarCollection.Add(newBar);
SelectedItem = newBar ;
_unsavedChanges = true;
}
什么是'BarCollection'的类型? –
@Ed'BarCollection'是一个'ObservableCollection' –
jonmicjam
我认为它必须是。有了这个假设,你的代码对我来说工作得很好。是否有可能新的项目以非常浅的灰色突出显示,与周围的窗口几乎没有区别?现代版本的Windows中默认的非聚焦高亮背景色可能难以注意。如果是这种情况,它很容易解决。 –