在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中默認的非聚焦高亮背景色可能難以注意。如果是這種情況,它很容易解決。 –