ListBox复选框命令绑定

问题描述 投票:0回答:1

我无法弄清楚这一点。我以为我有正确的装订设置,但它没有开火。所以我有一个观点:

<ListBox x:Name="EquipmentViewsListBox"
         ItemsSource="{Binding EquipmentViews, UpdateSourceTrigger=PropertyChanged}"
         SelectionMode="Extended"
         BorderThickness="0"
         Height="150"
         Margin="5,5,10,10">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                      Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=DataContext.ViewSelected}" 
                      CommandParameter="{Binding RelativeSource={RelativeSource Self}}" 
                      Content="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我想在每次选中ListBox中的复选框时触发命令。我在我的视图模型上创建了一个命令,如下所示:

public class SdddViewModel : ViewModelBase
{
    public SdddModel Model { get; set; }
    public RelayCommand<ViewWrapper> ViewSelected { get; set; }

    public SdddViewModel(SdddModel model)
    {
        Model = model;
        ViewSelected = new RelayCommand<ViewWrapper>(OnViewSelected);
    }

    private void OnViewSelected(ViewWrapper obj)
    {
        var asd = obj;
    }
}

所以我明白,当我做一个ListBox.ItemTemplate时,该项目的上下文变成了ListBoxItem所以在我的例子中是一个类对象ViewWrapper。这与Name绑定内容以及IsSelected属性一起工作正常。这是检查项目时未触发的命令。我把相对祖先设为ListBoxPath=DataContext,但仍然没有任何反应。想法?

c# wpf xaml mvvm mvvm-light
1个回答
2
投票

问题是CommandParameter不匹配。你宣布它是如此CommandParameterViewWrapper但你通过使用CheckBox发送了RelativeSource Self类型的参数。将CommandParameter更改为简单的{Binding},这意味着它发送DataContextListBoxItem,即ViewWrapper

您可以使用Snoop检测到此绑定错误。

© www.soinside.com 2019 - 2024. All rights reserved.