在 DataTemplate 中为 MenuItem 指定命令 [英] Specify Command for MenuItem in a DataTemplate

查看:10
本文介绍了在 DataTemplate 中为 MenuItem 指定命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个上下文菜单.它绑定到某个集合,并且它有一个像这样定义的 ItemTemplate:

I have a context menu. It's bound to some collection and it has a defined ItemTemplate like this:

<ContextMenu
    ItemsSource={Binding ...}
    ItemTemplate={StaticResource itemTemplate}
    />

itemTemplate 是一个带有 TextBlock 的简单 DataTemplate:

itemTemplate is a simple DataTemplate with a TextBlock:

<DataTemplate x:Key="itemTemplate">
    <TextBlock Text={Binding ...} />
</DataTemplate>

如何将 MenuItem 的 Command 属性绑定到基础对象的属性?

How do I bind Command property for MenuItem to the underlying object's property?

推荐答案

我认为您需要将 TextBlock 包装在 MenuItem 中:

I think you need to wrap your TextBlock in a MenuItem:

<DataTemplate x:Key="itemTemplate">
    <MenuItem Command={Binding ...}>
        <TextBlock Text={Binding ...} />
    </MenuItem>
</DataTemplate>

但我现在没有 IDE 来尝试这个.告诉我进展如何.

But I don't have an IDE in front of me right now to try this. Let me know how it goes.

看起来您需要使用 here.很抱歉一开始就让你走错了路 - 但我遇到了一个 IDE,这很有效:

Looks like you need to use the ItemContainerStyle as seen here. Sorry for leading you down the wrong path at the start there - but I got in front of an IDE and this works:

<ContextMenu.ItemContainerStyle>
    <Style TargetType="MenuItem">
        <Setter Property="Command" Value="{Binding ...}"/>
    </Style>
</ContextMenu.ItemContainerStyle>

这篇关于在 DataTemplate 中为 MenuItem 指定命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆