【问题标题】:Binding the IsSelected property of ListBoxItem to DataContext of Itemssource [closed]将 ListBoxItem 的 IsSelected 属性绑定到 Itemssource 的 DataContext [关闭]
【发布时间】:2017-08-11 17:01:05
【问题描述】:

我有一个定义了 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); } 
    }
}

我的 Listbox 所在视图的 ViewModel 如下所示:

public class ShellViewModel : BaseViewModel
{
    public ObservableCollection<MenuItemViewModel> MenuItems
    {
        get { return menuItems; }
        set { SetProperty(ref menuItems, value); }
    }
}

我的问题是如何将 ListBoxItem 的 IsSelected 属性绑定到 MenuItemViewModel 项目对象的 Selected 属性?

【问题讨论】:

  • 你现在的代码有什么问题?您没有提供可靠地重现问题的良好minimal reproducible example,并且您没有说明存在任何特定问题。您发布的那一点代码显然没有任何问题。那么,你的问题是什么?

标签: c# wpf xaml


【解决方案1】:
<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>

【讨论】:

    【解决方案2】:

    设置列表框的选中项属性

        SelectedItem="{Binding Path=SelectedMenuItem, Mode=TwoWay}"
    

    同时在您的 ShellViewModel 中创建 SelectedMenuItem

    ListBox 中的 SelectedItem 不是布尔值,所以如果你真的想将它绑定到 menuitem,那么你必须编写你的 IValueConvertor。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      相关资源
      最近更新 更多