Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c# - How to implement commands to use ancestor methods in WPF?

I have this context menu resource:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ContextMenu x:Key="FooContextMenu">
        <ContextMenu.CommandBindings>
            <CommandBinding Command="Help" Executed="{Binding ElementName=MainTabs, Path=HelpExecuted}" />
        </ContextMenu.CommandBindings>

        <MenuItem Command="Help">
            <MenuItem.Icon>
                <Image Source="../Resources/Icons/Help.png" Stretch="None" />
            </MenuItem.Icon>
        </MenuItem>
    </ContextMenu>
</ResourceDictionary>

I want to re-use it in two places. Firstly I'm trying to put it in a DataGrid:

<DataGrid ContextMenu="{DynamicResource FooContextMenu}">...

The ContextMenu itself works fine, but with the Executed="..." I have right now breaks the application and throws:

A first chance exception of type 'System.InvalidCastException' occurred in PresentationFramework.dll

Additional information: Unable to cast object of type 'System.Reflection.RuntimeEventInfo' to type 'System.Reflection.MethodInfo'.

If I remove the entire Executed="..." definition, then the code works (and the command does nothing/grayed out). The exception is thrown as soon as I right click the grid/open the context menu.

The DataGrid is placed under a few elements, but eventually they all are below a TabControl (called MainTabs) which has ItemsSource set to a collection of FooViewModels, and in that FooViewModel I have a method HelpExecuted which I want to be called.

Let's visualize:

  • TabControl (ItemsSource=ObservableCollection<FooViewModel>, x:Name=MainTabs)
    • Grid
      • More UI
        • DataGrid (with context menu set)

Why am I getting this error and how can I make the context menu command to "target" the FooViewModel's HelpExecuted method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Does this help?

<ContextMenu>
    <ContextMenu.ItemContainerStyle>
       <Style TargetType="MenuItem">
          <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=HelpExecuted}" />
       </Style>
    </ContextMenu.ItemContainerStyle>
    <MenuItem Header="Help" />
</ContextMenu>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...