相关疑难解决方法(0)

WPF ViewModel命令CanExecute问题

我的View Model上的Context Menu命令有些困难.

我正在为View Model中的每个命令实现ICommand接口,然后在View(MainWindow)的资源中创建ContextMenu,并使用MVVMToolkit中的CommandReference访问当前的DataContext(ViewModel)命令.

当我调试应用程序时,似乎除了创建窗口之外,没有调用命令上的CanExecute方法,因此我的Context MenuItems没有像我期望的那样启用或禁用.

我已经制作了一个简单的样本(附在这里),它表明了我的实际应用并总结如下.任何帮助将不胜感激!

这是ViewModel

namespace WpfCommandTest
{
    public class MainWindowViewModel
    {
        private List<string> data = new List<string>{ "One", "Two", "Three" };

        // This is to simplify this example - normally we would link to
        // Domain Model properties
        public List<string> TestData
        {
            get { return data; }
            set { data = value; }
        }

        // Bound Property for listview
        public string SelectedItem { get; set; }

        // Command to execute
        public ICommand DisplayValue …
Run Code Online (Sandbox Code Playgroud)

wpf binding command contextmenu icommand

12
推荐指数
1
解决办法
2万
查看次数

WPF - 为什么ContextMenu项目适用于ListBox而不适用于ItemsControl?

列表中的项目具有上下文菜单.上下文菜单项绑定到路由命令.

如果列表控件是a ListBox,则上下文菜单项可正常工作,但是一旦我将其降级为ItemsControl不再有效,它就会正常工作.具体来说,菜单项始终是灰色的.CanExecute我的回调CommandBinding也没有被调用.

它是什么ListBox允许上下文菜单项与命令正确绑定?

以下是一些示例应用程序的摘录,我将它们放在一起以突出显示问题:

<!-- Data template for items -->
<DataTemplate DataType="{x:Type local:Widget}">
  <StackPanel Orientation="Horizontal">
    <StackPanel.ContextMenu>
      <ContextMenu>
        <MenuItem Header="UseWidget" 
                  Command="{x:Static l:WidgetListControl.UseWidgetCommand}"
                  CommandParameter="{Binding}" />
      </ContextMenu>
    </StackPanel.ContextMenu>
    <TextBlock Text="{Binding Path=Name}" />
    <TextBlock Text="{Binding Path=Price}" />
  </StackPanel>
</DataTemplate>

<!-- Binding -->
<UserControl.CommandBindings>
  <CommandBinding Command="{x:Static l:WidgetListControl.UseWidgetCommand}" 
                  Executed="OnUseWidgetExecuted" 
                  CanExecute="CanUseWidgetExecute" />
</UserControl.CommandBindings>

<!-- ItemsControl doesn't work... -->
<ItemsControl ItemsSource="{Binding Path=Widgets}" />

<!-- But change it to ListBox, and it works! -->
<ListBox ItemsSource="{Binding Path=Widgets}" />
Run Code Online (Sandbox Code Playgroud)

这是视图模型和数据项的C#代码: …

.net wpf listbox itemscontrol routed-commands

3
推荐指数
1
解决办法
5948
查看次数