gpt4 book ai didi

wpf - 在 ItemsControl.DataTemplate 中为 ContextMenu 设置 DataContext

转载 作者:行者123 更新时间:2023-12-04 14:15:37 24 4
gpt4 key购买 nike

我有在 ItemsControl 的数据模板中使用的自定义控件。我想在每个项目上放置一个 ContextMenu 并让它调用 UserControl 的 View 模型来处理命令。使用下面的 XAML,我可以在自定义控件上获取单击事件,以在用户控件 View 模型中调用 SelectedItemCommand。但是,对上下文菜单使用类似的语法会失败。默认情况下,我获得每个自定义控件的 View 模式。我使用的任何 RelativeSource 语法值都不能解析为用户控件的 View 模型(RelativeSource Self)。

什么是魔法密码?

        <ItemsControl.ItemTemplate>
<DataTemplate>
<controls:MyCustomItem Width="Auto"
Command="{Binding DataContext.SelectedItemCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ItemsControl}}}"
CommandParameter="{Binding}">
<controls:MyCustomItem.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding DataContext.ClearAlarmsCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ItemsControl}}}"
Header="Clear All" />
</ContextMenu>
</controls:MyCustomItem.ContextMenu>
</controls:MyCustomItem>
</DataTemplate>
</ItemsControl.ItemTemplate>

最佳答案

ContextMenu doesn't lie in same Visual Tree 与 ItemsControl 一样。因此,RelativeSource 和 ElementName 在 Binding 中不起作用,因为它们遍历 Visual 树来找到源。

如果您使用的是 WPF 4.0 或更高版本,您可以使用 x:Reference 与 ItemsControl dataContext 绑定(bind)的标记扩展。

设置 x:Name在 ItemsControl 上并使用 x:Reference 绑定(bind)像这样:

<ItemsControl x:Name="itemsControl">
....
<MenuItem Command="{Binding DataContext.ClearAlarmsCommand,
Source={x:Reference itemsControl}}"
Header="Clear All" />
....
</ItemControl>

您也可以使用 Freezable BindingProxy 如果您的目标版本低于 WPF 4.0。引用我的回答 here对于方法。

关于wpf - 在 ItemsControl.DataTemplate 中为 ContextMenu 设置 DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25020594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com