0

I don't understand why CommandParameter binding ElementName=null in Datagrid Cat.Wpf

<Window x:Class="MyCat.Cat"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyCat"
        xmlns:vm ="clr-namespace:MyCat.ViewModel"
        mc:Ignorable="d" WindowStartupLocation="CenterScreen"
        Title="MyCat •" Height="650" Width="800">
<Window.DataContext>
  <vm:MyFriends/>
</Window.DataContext>

<Grid>
      <Grid.RowDefinitions>
        <RowDefinition Height="25"/>
        <RowDefinition/>
      </Grid.RowDefinitions>

      <Menu>
         <MenuItem Grid.Row="0" Grid.Column="0"
              Header="Show Name" x:Name="mimi" 
              Command="{Binding GetNameCat}"
              CommandParameter="{Binding ElementName=mimi}"/>
      </Menu>
      <DataGrid CanUserAddRows="False" CanUserDeleteRows="False" 
              Grid.Row="1" Grid.Column="0"
              SelectionUnit="FullRow">
              <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="List cats" x:Name="cats"
                              Command="{Binding GetCats}"
                              CommandParameter="{Binding ElementName=cats}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
      </DataGrid>

CommandParameter="{Binding ElementName=mimi}" work, but CommandParameter="{Binding ElementName=cats} not work. It always return null. I find out solution CommandParameter="{Binding RelativeSource={RelativeSource Self}}".

Some body, please tell me why?

tvc12
  • 198
  • 1
  • 10
  • 1
    The problem is the `ContextMenu`. The `ContextMenu` is not part of the `VisualTree`. See [WPF ContextMenu woes: How do I set the DataContext of the ContextMenu?](https://stackoverflow.com/questions/15033522/wpf-contextmenu-woes-how-do-i-set-the-datacontext-of-the-contextmenu) – Martin Backasch Mar 05 '19 at 12:01
  • You're passing a menuitem to a command? Why would you want to do that? – Andy Mar 05 '19 at 12:32
  • @Andy Yes, i want passing a menuitem to a command with parameter as object. In that case, i don't understand why have different between menuitem in menu and menuitem in contextmenu. – tvc12 Mar 05 '19 at 14:54
  • @MartinBackasch thank you, I understand – tvc12 Mar 05 '19 at 14:55

0 Answers0