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
562 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 Answer

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}}"

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

...