【问题标题】:ContextMenu commands on DataGrid Row do not workDataGrid Row 上的 ContextMenu 命令不起作用
【发布时间】:2016-08-11 11:54:37
【问题描述】:

我创建了一个样式,而不是将其绑定到 DataGrid.RowStyle Row 样式。 ContextMenu 出现,我可以从菜单项中进行选择,但 command 不会执行。我用其他控件测试了 command 并且工作正常。

<Style x:Key="DataGridRow"  TargetType="{x:Type DataGridRow}">
     <Setter Property="ContextMenu">
         <Setter.Value>
              <ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
                    <MenuItem Header="Add" Command="{Binding AddMessageContextMenu_Command}"/>
                    <MenuItem Header="Edit" Command="{Binding EditMessage_Command}"/>
              </ContextMenu>
           </Setter.Value>
     </Setter>
<Style>

<DataGrid Name="SearchTableDataGrid" ItemsSource="{Binding SearchTableDataGrid_ItemSource}"
   <DataGrid.RowStyle>
     <Style TargetType="{x:Type DataGridRow}">
          <Style.Triggers>
             <Trigger Property="AlternationIndex" Value="0">
                   <Setter Property="Background" Value="#FBFCFC" />
              </Trigger>
              <Trigger Property="AlternationIndex" Value="1">
                   <Setter Property="Background" Value="#f6f8f8" />
              </Trigger>
          </Style.Triggers>
      </Style>
   </DataGrid.RowStyle>
</DataGrid>

【问题讨论】:

  • 我使用了标签,但命令仍然没有执行。
  • 您需要在运行时使用 Visual Studio 2015 中的工具或类似 Snoop 的工具检查您的绑定。

标签: wpf mvvm datagrid row


【解决方案1】:

您需要对正确 DataContext 的引用。正如 cmets 中所建议的,您可以为此使用 Rows Tag 属性。

下面的代码进入 Windows DataContext

<Style TargetType="{x:Type DataGridRow}">
    <Setter Property="Tag" 
            Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, 
                            Path=DataContext}"/>
    <Setter Property="ContextMenu">
        <Setter.Value>
            <ContextMenu DataContext="{Binding PlacementTarget.Tag, 
                                               RelativeSource={RelativeSource Self}}">
                <MenuItem Header="Add" Command="{Binding AddMessageContextMenu_Command}"/>
                <MenuItem Header="Edit" Command="{Binding EditMessage_Command}"/>
            </ContextMenu>
        </Setter.Value>
    </Setter>
</Style>

【讨论】:

  • 谢谢,我声明了一个不同的 RelativeSource。现在它绑定到正确的命令。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 2015-03-13
  • 1970-01-01
相关资源
最近更新 更多