Question

I am using context menu on DataGrid.

I want each item will display context menu item by the entity that been right clicked. In case that there is no entity the context menu item list will be empty so in this case I don't want the context menu to be visible to the user with empty items. (I see on empty rectangle that will confuse the user).

My code look like this:

<ContextMenu Name="cm" ItemsSource="{Binding DemoInstance.ContextMenuItems}"  
             ItemContainerStyle="{StaticResource demo2Style}" >
     <Style TargetType="{x:Type ContextMenu}">
        <Style.Triggers>
           <Trigger Property="HasItems" Value="False">
              <Setter Property="Visibility" Value="Collapsed" />
          </Trigger>
       </Style.Triggers>
     </Style>
</ContextMenu>

when i am using it i get the exception:

"An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

Additional information: Items collection must be empty before using ItemsSource."

Why this is happening and how can I solve it?

Was it helpful?

Solution

Place ContextMenu style under <ContextMenu.Style> tags:

<ContextMenu Name="cm" ItemsSource="{Binding DemoInstance.ContextMenuItems}"  
             ItemContainerStyle="{StaticResource demo2Style}" >
  <ContextMenu.Style>
     <Style TargetType="{x:Type ContextMenu}">
        <Style.Triggers>
           <Trigger Property="HasItems" Value="False">
              <Setter Property="Visibility" Value="Collapsed" />
          </Trigger>
       </Style.Triggers>
     </Style>
  </ContextMenu.Style>
</ContextMenu>

OTHER TIPS

The problem is with your XAML. You added a Style as a child of the ContextMenu, and also binded it's ItemsSource property. (Setting both is not possible see here for more info.)

But from your code I suspect that you most likely want something like this:

Resources part (where your demo2Style resides):

<Style x:Key="myCustomStyle" TargetType="{x:Type ContextMenu}">
    <Style.Triggers>
        <Trigger Property="HasItems" Value="False">
            <Setter Property="Visibility" Value="Collapsed" />
        </Trigger>
    </Style.Triggers>  
</Style>

And the ContextMenu:

    <ContextMenu Name="cm" 
                 ItemsSource="{Binding DemoInstance.ContextMenuItems}" 
                 ItemContainerStyle="{StaticResource demo2Style}"
                 Style="{StaticResource myCustomStyle}" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top