【问题标题】:Reference Parent MenuItem in ItemContainerStyle在 ItemContainerStyle 中引用父 MenuItem
【发布时间】:2013-06-16 22:44:26
【问题描述】:

我正在尝试将自动创建的菜单项的命令绑定到由父 MenuItem 的 ViewModel 公开的 ICommand。希望以下内容能很好地代表我所拥有的:

自定义控件:

class MyMenuItem : MenuItem {}

视图模型:

class ParentVM
{
    public IEnumerable<ChildVM> Children { get; set; }
    public ICommand TheCommand { get; set; }
}

class ChildVM
{
    public string Name { get; set; }
}

自定义控件的全局样式:

<Style TargetType="namespace:MyMenuItem">
    <Setter Property="Header" Value="Some Text"/>
    <Setter Property="ItemsSource" Value="{Binding Children}"/>
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="MenuItem"/>
                <Setter Property="Command" Value="{Binding [parent].TheCommand}"/>
                <Setter Property="Header" Value="{Binding Name}"/>
            </Style>
        </Setter.Value>
    </Setter>
</Style>

在上下文菜单中使用:

<ContextMenu>
    <namespace:MyMenuItem DataContext="{Binding AParentVM}"/>
</ContextMenu>

我需要知道与 [parent] 相关的内容。确实创建了子菜单项并且它们的名称显示正确,这告诉我我在顶层有正确的 DataContext,因为“Children”绑定正确,而我在底层拥有正确的 DataContext,因为“Name”绑定正确。我希望使用 MyMenuItem 的 AncestorType 进行 RelativeSource 绑定,但它不起作用。

【问题讨论】:

    标签: c# wpf xaml viewmodel datacontext


    【解决方案1】:
    <Setter Property="Command" Value="{Binding DataContext.TheCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type namespace:MyMenuItem}}}"/>
    

    或者,给子虚拟机一个对父虚拟机的引用,或者它需要公开的命令。

    【讨论】:

    • 我相信你需要绑定到DataContext.TheCommand,所以你绑定到MyMenuItem.DataContext.TheCommand而不是尝试绑定到不存在的MyMenuItem.TheCommand
    • 谢谢瑞秋,就是这样。这个周末太多的xaml。让它成为答案,我会奖励。
    • +1 更新答案。 @PatrickV 这个答案是正确的,所以我不会单独发布答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多