Search code examples
c#wpfmenuitem

WPF MenuItem: How to bind a SubMenuItem command to to its Parent MenuItem


I want to Bind the e.g. "Debug|Any CPU" MenuItem Command which has its own BuildConfiguration Context to the Project Context BuildProjectCommand. How to do it correctly?

I already tried to accomplish this with FindAncestor but it won't work. e.g. Command="{Binding Path=DataContext.BuildCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}}"

See picture for more understanding: enter image description here


Solution

  • I've made a quick prototype and binding below should work as you expect:

    <DataTemplate DataType="{x:Type commmon:BuildConfiguration}">
        <TextBlock x:Name="ConfigBlock">
            <Run Text="{Binding Name, Mode=OneWay}"/>
            <TextBlock.InputBindings>
                <MouseBinding MouseAction="LeftClick" 
                              Command="{Binding DataContext.BuildCommand, 
                              RelativeSource={RelativeSource AncestorLevel=2, 
                              AncestorType={x:Type MenuItem}}}">
                </MouseBinding>
            </TextBlock.InputBindings>
        </TextBlock>
    </DataTemplate>