【问题标题】:How to set a binding in WPF Toolkit Datagrid's ContextMenu CommandParameter如何在 WPF Toolkit Datagrid 的 ContextMenu CommandParameter 中设置绑定
【发布时间】:2011-02-20 05:03:17
【问题描述】:

我需要创建一个 ContextMenu,我想在其中使用 CommandParameter 将数据网格的当前选定索引传递给 ViewModel。以下 Xaml 代码不起作用。可能是什么问题?

<dg:DataGrid ItemsSource="{Binding MarketsRows}"
    <dg:DataGrid.ContextMenu >
        <ContextMenu >
            <MenuItem Header="Add Divider"
                  CommandParameter="{Binding Path=SelectedIndex,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type dg:DataGrid}}}"
                  Command="{Binding Path= AddDividerCommand}"/>
        </ContextMenu>
    </dg:DataGrid.ContextMenu>
</dg:DataGrid>

【问题讨论】:

  • 您在调试应用程序时是否检查过调试控制台?如果这是一个绑定问题,您可能会在那里找到一些用于对其进行故障排除的数据......
  • 我确实遇到了绑定错误,我只是不知道如何解决它:System.Windows.Data 错误:4:无法通过引用 'RelativeSource FindAncestor,AncestorType='Microsoft 找到绑定源.Windows.Controls.DataGrid',AncestorLevel='1''。绑定表达式:路径=选定索引;数据项=空;目标元素是'MenuItem'(名称='');目标属性是'CommandParameter'(类型'Object')

标签: c# wpf xaml binding


【解决方案1】:

上下文菜单不是同一可视树的一部分。祖先绑定不起作用,因为上下文菜单不是它所在元素的子元素;在你的情况下,数据网格。

有一些解决方法,我之前回答过这个问题 herehere (kind of)

但是您正在寻找的是执行此类操作的放置目标(只要 AddDividerCommand 是数据网格上的属性(即放置目标)

<ContextMenu DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget}">
 <MenuItem
    Header="Add Divider"
    CommandParameter="{Binding Path=SelectedIndex}"
    Command="{Binding Path=AddDividerCommand}"/>
</ContextMenu>

【讨论】:

  • 有效!!!谢谢!我只需要稍微修改 DataContext:DataContext="{Binding RelativeSource={RelativeSource Mode=Self}, Path=PlacementTarget.DataContext}"
【解决方案2】:

在您的 CommandParameter 中尝试这样的操作,

<DataGrid.ContextMenu>
     <ContextMenu>
           <MenuItem Header="MyHeader" 
                     Command="{Binding MyCommand}"
                     CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItem}" />
</DataGrid.ContextMenu>

我已经测试过了,它应该可以工作。

【讨论】:

    猜你喜欢
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 2012-08-23
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多