WPF XAML - Как отправить параметр в шаблон?

У меня есть ContentControl с сеткой в ​​нем. Существует шаблон для ContextMenu каждого ListBoxItem. ContextMenu выглядит следующим образом:

<ContentControl.Resources>
    <ContextMenu x:Key="SimpleDataObjectContextMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
        <MenuItem Header="Create" Command="{Binding AddRelation}" CommandParameter="..Name..of..caller.."/>
        <MenuItem Header="Delete" Command="{Binding DeleteRelation}" CommandParameter="..Name..of..caller.."//>
    </ContextMenu>
</ContentControl.Resources>

Сетка выглядит так:

<Grid>
    <Rectangle x:Name="LeftRectangle" Width="5" Height="5" Fill="Black" Margin="5" ContextMenu="{StaticResource SimpleDataObjectContextMenu}"/>
    <TextBlock Text="{Binding Model.Name}"/>
    <Rectangle x:Name="RightRectangle" Width="5" Height="5" Fill="Black" Margin="5" ContextMenu="{StaticResource SimpleDataObjectContextMenu}"/>
</Grid>

Я хочу передать из "LeftRectangle" и "RightRectangle" (которые используют собственный шаблон ContextMenu "SimpleDataObjectContextMenu") x:Name в "SimpleDataObjectContextMenu", чтобы я мог передать это имя как CommandParameter в шаблоне.

Вместо..Name..of..caller.. например, я хочу отправить "LeftRectangle", если ContextMenu было открыто в левом прямоугольнике...

Любая идея, как я могу понять это?

2 ответа

Решение

Удалить DataContext обязательный от вашего ContextMenu:

<ContextMenu x:Key="SimpleDataObjectContextMenu" >
    <MenuItem Header="Create" Command="{Binding AddRelation}" CommandParameter="{Binding Parent.PlacementTarget.Name, RelativeSource={RelativeSource Self}}"/>
    <MenuItem Header="Delete" Command="{Binding DeleteRelation}" CommandParameter="{Binding Parent.PlacementTarget.Name, RelativeSource={RelativeSource Self}}"/>
</ContextMenu>

Вы можете привязать параметр команды следующим образом

 CommandParameter="{Binding Path=Menu.UIElement, RelativeSource={RelativeSource Self}

и в коде позади вы можете привести параметр с Rectangle, как это

      var rectangle = parameter as Rectangle ;
      if(rectangle != null)
      {
       var name = rectangle.Name;
      }
Другие вопросы по тегам