Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - RelativeSource binding not resolving

I have a ContextMenu in a TreeView

UserControl (DataContext=ViewModel)
    |
    |
    ---- TreeView (ItemSource=MyItems)
           |
           |
           ----- Items (ItemSource=MyChildrenItems)
                   |
                   |
                   ----- ContextMenu

I want to bind the Command of the ContextMenuItem to a RelayCommand in the ViewModel, I tried all kinds of RelativeSource bindings, but nothing seems to work...

How should I configure the RelativeSource binding?

<ContextMenu>
    <MenuItem
        Header="Bla"
        Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=TreeView}, Path=DataContext.MyRelayCommand}" />

I get binding errors like

Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TreeView', AncestorLevel='1''. BindingExpression:Path=DataContext.ExcludeSeasonCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Finally, after many many many google searches I ran into the solution

<MenuItem
    Header="Exclude season"
    Command="{Binding DataContext.MyRelayCommand, Source={x:Reference _myTreeView}}" />

Because the HierarchicalDataTemplate does not appear in the visual tree, there is not "relative" source...

I hope this helps somebody else who's pulling his/her hair out...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...