【问题标题】:Why is my CommandParameter null when I have the Path as SelectedItem?当我将路径作为 SelectedItem 时,为什么我的 CommandParameter 为空?
【发布时间】:2019-06-18 13:04:26
【问题描述】:

所以我尝试将SelectedItem 作为参数传递,以便我可以使用绑定到它的数据。

基本上我想打开一个MessageBox 并显示绑定该项目的用户的Name 属性。

这是我的 xaml

<ItemsControl ItemsSource="{Binding CardViewModel.Users}"
                          dd:DragDrop.IsDragSource="True"
                          dd:DragDrop.IsDropTarget="True"
                          dd:DragDrop.UseDefaultEffectDataTemplate="True">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <controls:UserCard>
                            <controls:UserCard.ContextMenu>
                                <!-- Bind the DataContext of the CM to the DataContext that's bound to the RootObject-->
                                <ContextMenu DataContext="{Binding DataContext, Source={local:RootObject}}">
                                    <MenuItem Header="Edit"
                                              Command="{Binding CardViewModel.EditUser}" 
                                              CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}},
                                              Path=PlacementTarget.SelectedItem}"/>
                                </ContextMenu>
                            </controls:UserCard.ContextMenu>
                        </controls:UserCard>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>

            </ItemsControl>

该命令工作正常,除了当我单击MenuItem 并触发命令时,我在操作所在的位置放置了一个断点,并将参数显示为null,我怀疑它是我谁绑定错了。

public void DisplayEditUser(object user)
{
    if (user != null)
    {
        MessageBox.Show("Not null");
    }
}

【问题讨论】:

    标签: c# .net wpf mvvm data-binding


    【解决方案1】:

    问题是ContextMenu.PlacementTarget 不是ItemsControl 而是UserCard,所以绑定源解析绝对会失败。要解决它,您需要将ItemsControl.SelectedItem 绑定到UserCard 的一个属性,例如Tag 作为中继。

    <controls:UserCard Tag="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=ListBox}}">
    
    CommandParameter="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
    

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      相关资源
      最近更新 更多