Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Why can't I use DataContext={Binding} for my context menu?

I have code that looks something like this:

<HierarchicalDataTemplate
    DataType="{x:Type local:SomeType}"
    ItemsSource="{Binding SomeOtherItems}"
    >
    <DockPanel Margin="4">
        <DockPanel.ContextMenu>
            <local:SomeContextMenu DataContext="{Binding}" />
        </DockPanel.ContextMenu>
        <CheckBox IsChecked="{Binding SomeBooleanProperty, Mode=TwoWay}" />
        <TextBlock
            Margin="4,0"
            Text="{Binding Name}" />
    </DockPanel>
</HierarchicalDataTemplate>

Without the context menu, everything works as expected. But when I add these lines:

<DockPanel.ContextMenu>
    <local:SomeContextMenu DataContext="{Binding}" />
</DockPanel.ContextMenu>

I get this (runtime) error for each element that uses the HierarchicalDataTemplate:

System.Windows.Data Error: 3 : Cannot find element that provides DataContext. BindingExpression:(no path); DataItem=null; target element is 'SomeContextMenu' (Name=''); target property is 'DataContext' (type 'Object')

Why do the Bindings work for everything except the context menu, but not for the context menu?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

First of all, DataContext="{Binding}" does not make much sense as that would bind the DataContext to the DataContext. The problem here is probably that the ContextMenu is not in the logical tree, and its visual tree is disconnected since ContextMenus are floating popups.

Try binding the DataContext via the PlacementTarget:

 DataContext="{Binding PlacementTarget.DataContext,
                       RelativeSource={RelativeSource Self}}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...