开发者

How to set a binding in WPF Toolkit Datagrid's ContextMenu CommandParameter

开发者 https://www.devze.com 2022-12-30 06:23 出处:网络
I need to create a ContextMenu where I want to pass a currently selected index of the datagrid to a ViewModel using CommandParameter. The following Xaml code doesn\'t work. What might be the problem?

I need to create a ContextMenu where I want to pass a currently selected index of the datagrid to a ViewModel using CommandParameter. The following Xaml code doesn't work. What might be the problem?

<dg:DataGrid ItemsSource="{Binding MarketsRows}"
    <dg:DataGrid.ContextMenu >
        <ContextMenu >
            <开发者_C百科;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>


A context menu is not part of the same visual tree. Ancestor bindings dont work as the context menu is not a child of the element it is on; in your case the datagrid.

There are some workarounds, Ive answered this question previously here and here (kind of)

But what you are looking for is the placement target to do something like this (as long as AddDividerCommand is a property on the datagrid(i.e. the placement target)

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


Try something like this in your CommandParameter,

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

I already tested it and it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消