繁体   English   中英

WPF:获取具有模板样式的ListBoxItem作为CheckBox并与IsSelected同步

[英]WPF: Get a ListBoxItem as CheckBox with a Template Style to synchronize with IsSelected

我正在制作MVVM WPF应用程序,在此应用程序中,我有一个带有我自己的特权项的ListBox。

很久以后,我终于找到了一种解决方案 ,该方法如何使选择与我的ViewModel同步。 (您还需要在您的项目类中实现IEquatable)

问题

现在,我想将ListBoxItems设置为CheckBoxes的样式,有很多解决此问题的方法,但是没有一个真正适合我的需求。

所以我想出了这个解决方案,因为我可以仅将这种样式应用于所需的ListBox,而不必担心DisplayMemberPath或Items样式为CheckBox ListBoxItems。

视图:

<ListBox Grid.Row="5" Grid.Column="1"
         ItemsSource="{Binding Privileges}"
         BehavExt:SelectedItems.Items="{Binding SelectedPrivileges}"
         SelectionMode="Multiple"
         DisplayMemberPath="Name"
         Style="{StaticResource CheckBoxListBox}"/>

样式:

<Style x:Key="CheckBoxListBox"
       TargetType="{x:Type ListBox}"
       BasedOn="{StaticResource MetroListBox}">

    <Setter Property="Margin" Value="5" />
    <Setter Property="ItemContainerStyle"
            Value="{DynamicResource CheckBoxListBoxItem}" />
</Style>

<Style x:Key="CheckBoxListBoxItem"
       TargetType="{x:Type ListBoxItem}"
       BasedOn="{StaticResource MetroListBoxItem}">

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <CheckBox IsChecked="{TemplateBinding Property=IsSelected}">
                    <ContentPresenter />
                </CheckBox>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

ViewModel:

private ObservableCollection<Privilege> _privileges;
public ObservableCollection<Privilege> Privileges
{
    get { return _privileges; }
    set {
        _privileges = value;
        RaisePropertyChanged(() => Privileges);
    }
}

private ObservableCollection<Privilege> _selectedPrivileges;
public ObservableCollection<Privilege> SelectedPrivileges
{
    get { return _selectedPrivileges; }
    set
    {
        _selectedPrivileges = value;
        RaisePropertyChanged(() => SelectedPrivileges);
    }
}

问题是这一行:

IsChecked="{TemplateBinding Property=IsSelected}"

它工作正常,但仅在一个方向上有效。 当在代码中将一个项目添加到我的SelectedPrivileges中时,它将显示为选中状态,但是当我在GUI中选中该项目时,它将不会执行任何操作。 (没有CheckBox样式,它就起作用了,这是因为TemplateBinding仅在一个方向上起作用)

我该如何工作? 我虽然有一些类似扳机的东西,但是我不知道如何实现这一点。

我相信您要找的东西实际上非常简单。 您需要更改IsChecked属性的绑定的绑定模式,如下所示:

{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected, Mode=TwoWay}

那应该做。

在这个出色的备忘单上可以找到这个以及基本上所有其他WPF绑定技巧。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM