【问题标题】:Binding to two different DataContexts in a ContextMenu绑定到 ContextMenu 中的两个不同 DataContext
【发布时间】:2011-12-27 09:33:57
【问题描述】:

我正在尝试从 DataTemplate 中绑定到容器的属性。我的标记的简化版本如下所示:

<Grid>
<Grid.Resources>

<DataTemplate DataType="{x:Type myCustomItem}">

    <!--Visual stuff-->

    <StackPanel>
        <StackPanel.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Add Item" 
                          Command="{Binding myCustomItemsICommand}"
                          CommandParameter="{Binding RelativeSource={RelativeSource  Mode=FindAncestor, AncestorType={x:Type CustomContainerType}}, Path=ContainerProperty}"/>   
            </ContextMenu>
         </StackPanel.ContextMenu>   
     </StackPanel>                                                            
</DataTemplate>

</Grid.Resources>

<CustomContainerType/>

</Grid>

我的方法基于this post,但它似乎不起作用。该问题似乎是由于 ContextMenu 在可视化树中的放置引起的。基本上我正在尝试将 Command 绑定到 DataTemplate 的 DataContext,但将 CommandParameter 绑定到 DataTemplate 之外的 DataContext。

【问题讨论】:

    标签: wpf xaml data-binding datatemplate


    【解决方案1】:

    ContextMenus 与其他控件不在同一个可视化树中,关于如何跨该边界进行绑定存在一些问题,但如果不指定名称,这可能会有些困难。

    ElementName 也因缺少树连接而失败,但您可以在 Binding.Source 中使用 x:Reference

    【讨论】:

    • 谢谢! Source={x:Reference Name=theElementName} 方法奏效了。
    猜你喜欢
    • 2018-08-29
    • 2016-11-25
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多