WPF中如何找到父的SelectItems

在DataGrid中,我们经常会需要找到选中的项绑定到Command中,然后再Command中处理一些逻辑,但是不知道怎么绑定,来看看我是怎么做的吧:

<Setter Property="CommandParameter"
        Value="{Binding Path=SelectedItems, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />

或者

CommandParameter="{Binding Path=SelectedItems, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"

再DataGrid中有时候需要右键菜单,那该怎么做呢?

    <DataGrid.ContextMenu>
                <ContextMenu x:Name="dgmenu1" StaysOpen="true">
                    <MenuItem Header="打开" Command="{Binding OpenCommand}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>

但是在ContextMenu中,经常会在command中传递参数,假如我们需要把SelectedItems传递给VM,我试过好多次,都不成功,最后终于解决了:

<Setter Property="CommandParameter"
                    Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}},
                                    Path=PlacementTarget.SelectedItems}" />

我加粗的地方是重点,理解了这2个地方就知道怎么传了。

PlacementTarget:得到ContextMenu的Owner

这样一来就明白了。

原文地址:https://www.cnblogs.com/qizh/p/3447381.html