【问题标题】:ListBox checkbox command bindingListBox 复选框命令绑定
【发布时间】:2018-03-04 15:53:06
【问题描述】:

我想不通。我以为我正确设置了绑定,但它没有触发。所以我有一个看法:

<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】:

    问题是CommandParameter 不匹配。你声明了它,所以CommandParameterViewWrapper,但你使用RelativeSource Self 发送了CheckBox 类型的参数。将CommandParameter 更改为简单的{Binding},这意味着它发送ListBoxItemDataContext,即ViewWrapper

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

    【讨论】:

    • 哥们,你真是个天才!所以我至少期望堆栈跟踪会抛出异常或其他东西,而不是什么都不做。我现在正在安装 Snoop。非常感谢。
    • 绑定错误不会引发异常,但您也可以在“输出”窗口中看到它们......但是,Snoop 是必须的
    猜你喜欢
    • 2014-11-16
    • 2016-10-11
    • 2017-07-22
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多