Noxxys
Noxxys

Reputation: 919

ContextMenu in Window Resources, bind to DataGrid property

I would like to reuse a ContextMenu on several DataGrid. So I placed the context menu in the Resources of my Window.

I have trouble to bind to the SelectedItem property of the DataGrid on which the ContextMenu is placed.

In this example, I'm trying to have the Name property of the SelectedItem displayed in the context menu.

<Window.Resources>
    <ContextMenu x:Key="DgContextMenu" 
        DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
        <MenuItem Header="{Binding SelectedItem.Name, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
    </ContextMenu>
</Window.Resources>

<DataGrid ItemsSource="{Binding CollectionView}" 
    ContextMenu="{StaticResource DgContextMenu}" 
    Tag="{Binding DataContext, RelativeSource={RelativeSource Self}}">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Name" Binding="{Binding Name}" />
    </DataGrid.Columns>
</DataGrid>

Thanks in advance

Upvotes: 0

Views: 1196

Answers (1)

user1018735
user1018735

Reputation: 218

The way you have written your example has binding error and that's why your context menu doesn't work. You have binded menu item header to SelectedItem.Name of ContextMenu object which doesn't have SelectedItem property (you can tell that from RelativeSource part of the menu item binding). One possible solution, among others, would be to bind DataContext of ContextMenu to DataGrid through PlacementTarget (not PlacementTarget.Tag). Since child controls „inherit“ DataContext of the parent you can just specify Path in the menu item binding. This is how it would look:

<Window.Resources>
    <ContextMenu x:Key="DgContextMenu" 
             DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource Self}}">
        <MenuItem Header="{Binding Path=SelectedItem.Name}" />
    </ContextMenu>
</Window.Resources>

<DataGrid ItemsSource="{Binding CollectionView}" 
      ContextMenu="{StaticResource DgContextMenu}" 
      >
</DataGrid>

Basically you can find those errors if you run application in VS debugger and watch output in Output window (Debug -> Window -> Output). In output window you should look for System.Windows.Data Error line and in that line you will see the type of an object and property you are trying to bind and that will give you a clue what's wrong with your binding in XAML.

Upvotes: 2

Related Questions