我有一个定义了Itemssource的ListBox:
<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接口,如下所示:
public class MenuItemViewModel : BaseViewModel
{
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set { SetProperty(ref isSelected, value); }
}
}
我的列表框所在的视图的ViewModel如下所示:
public class ShellViewModel : BaseViewModel
{
public ObservableCollection<MenuItemViewModel> MenuItems
{
get { return menuItems; }
set { SetProperty(ref menuItems, value); }
}
}
我的问题是如何将ListBoxItem的IsSelected属性绑定到MenuItemViewModel项目对象的Selected属性?
答案 0 :(得分:2)
<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>
答案 1 :(得分:0)
设置列表框的选定项目道具
SelectedItem="{Binding Path=SelectedMenuItem, Mode=TwoWay}"
还在ShellViewModel中创建SelectedMenuItem
ListBox中的SelectedItem不是布尔值,所以如果你真的想将它绑定到menuitem,那么你必须编写你的IValueConvertor。