将 ListBoxItem 的 IsSelected 属性绑定到 Itemssource 的 DataContext [英] Binding the IsSelected property of ListBoxItem to DataContext of Itemssource
本文介绍了将 ListBoxItem 的 IsSelected 属性绑定到 Itemssource 的 DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个定义了 Itemssource 的 ListBox:
I have an ListBox with an Itemssource defined:
<ListBox
x:Name="ModuleListBox"
DockPanel.Dock="Top"
ItemsSource="{Binding MenuItems}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
我的 MenuItems ViewModel 实现了 INotifyChanged 接口,如下所示:
My MenuItems ViewModel implements the INotifyChanged Interface and looks like:
public class MenuItemViewModel : BaseViewModel
{
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set { SetProperty(ref isSelected, value); }
}
}
我的列表框所在的视图的视图模型如下所示:
The ViewModel of the View where my Listbox lives in looks like:
public class ShellViewModel : BaseViewModel
{
public ObservableCollection<MenuItemViewModel> MenuItems
{
get { return menuItems; }
set { SetProperty(ref menuItems, value); }
}
}
我的问题是如何将 ListBoxItem 的 IsSelected 属性绑定到 MenuItemViewModel 项目对象的 Selected 属性?
My Question is how can i bind the IsSelected Property of the ListBoxItem to the Selected property of MenuItemViewModel item object?
推荐答案
<ListBox
x:Name="ModuleListBox"
DockPanel.Dock="Top"
ItemsSource="{Binding MenuItems}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding RelativeSource={RelativeSource Self}, Path=DataContext.IsSelected}" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
这篇关于将 ListBoxItem 的 IsSelected 属性绑定到 Itemssource 的 DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文