© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
1 reply
stigzler

✅ WPF - Accessing a TreeViewItem's root UserControl DataContext for a Command

I am trying to execute a Command which exists in the ViewModel bound to the root parent UserControl of a child TreeViewItem. This is from a ContextMenu bound to root TreeViewItems. The TreeView code:

Key code:

<StackPanel.ContextMenu>
    <ContextMenu Style="{StaticResource ContextMenu}">
        <MenuItem Header="Delete Gist" Background="{DynamicResource {x:Static vsshell:VsBrushes.WindowKey}}"
                  Style="{StaticResource MenuItem}" 
                  Command="{Binding 
                        RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type viewmodels:MainWindowViewModel}},
                        Path=DataContext.DeleteGistCMD}">
            <MenuItem.Icon>
                <imaging:CrispImage Moniker="{x:Static catalog:KnownMonikers.DeleteListItem}"/>
            </MenuItem.Icon>
        </MenuItem>
    </ContextMenu>
</StackPanel.ContextMenu>
<StackPanel.ContextMenu>
    <ContextMenu Style="{StaticResource ContextMenu}">
        <MenuItem Header="Delete Gist" Background="{DynamicResource {x:Static vsshell:VsBrushes.WindowKey}}"
                  Style="{StaticResource MenuItem}" 
                  Command="{Binding 
                        RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type viewmodels:MainWindowViewModel}},
                        Path=DataContext.DeleteGistCMD}">
            <MenuItem.Icon>
                <imaging:CrispImage Moniker="{x:Static catalog:KnownMonikers.DeleteListItem}"/>
            </MenuItem.Icon>
        </MenuItem>
    </ContextMenu>
</StackPanel.ContextMenu>


Broader context:
https://paste.mod.gg/khruicdqkfhy/1

MainWindowViewModel
MainWindowViewModel
is the DataContext of MainWindow, within which the Command I'm targeting exists. I've tried various permutations of RelativeSource for Binding, as despite xaml intellisense suggesting the binding is right by offering the command as an option, it doesn't fire on selecting the relevant ContextMenuItem.

Any ideas?
BlazeBin - khruicdqkfhy
A tool for sharing your source code with the world!
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ DataContext & UserControl
C#CC# / help
3y ago
❔ Datacontext WPF?
C#CC# / help
3y ago
❔ How put specific UserControl to ContentControl baseing on DataContext.
C#CC# / help
4y ago
❔ WPF command
C#CC# / help
4y ago