WPF MenuItem样式参数在第一次打开菜单上不可用 [英] WPF MenuItem style parameters not available on menu first open
问题描述
我要在TreeViewItem的ControlTemplate中指定一个上下文菜单,如下所示:
I am specifying a context menu within the ControlTemplate of a TreeViewItem as follows:
<ContextMenu ItemsSource="{Binding Commands}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding CommandParameter}" />
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="Icon" Value="{Binding Icon}" />
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
其中Commands是具有以下签名的ICommandViewModels对象的列表:
where Commands is a list of ICommandViewModels objects with the following signature:
public interface ICommandViewModel
{
string Name { get; }
Image Icon { get; }
ICommand Command { get; set; }
object CommandParameter { get; set; }
}
当ContextMenu打开时,传递给Command的CommandParamter最初为null,这将按指定禁用Command.如果Command.CanExecute始终返回true,则这不是问题,因为Command.Execute最终将获得正确的CommandParameter.在某些情况下,如果CommandParamter为null,则不允许执行Command,因此这会成为问题.
When the ContextMenu is open, CommandParamter being passed to Command is initially null, which disables Command as specified. If Command.CanExecute always return true, this is not a problem, as Command.Execute eventually gets the correct CommandParameter. In some cases, Command is not allowed to execute if CommandParamter is null, so this becomes a problem.
任何对这里发生的事情有理论认识并可能解决的人吗?
Anyone with a theory on what is going on here and a possible fix?
TIA.
推荐答案
尝试交换CommandParameter
和Command
属性设置器.我不确定这种行为的原因,但是看起来它不重新查询可以在CommandParameter更改后执行.此处介绍了另一种修复方法. http://compositewpf.codeplex.com/Thread /View.aspx?ThreadId=47338
Try swaping CommandParameter
and Command
property setters. I'm not sure about the reason of such behavior, but is looks like it doesn't requery can execute on CommandParameter changed. Another way is of fixing is described here http://compositewpf.codeplex.com/Thread/View.aspx?ThreadId=47338
这篇关于WPF MenuItem样式参数在第一次打开菜单上不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!