【问题标题】:AppCommand are not supported in a Windows Presentation Foundation (WPF) projectWindows Presentation Foundation (WPF) 项目不支持 AppCommand
【发布时间】:2014-04-13 21:31:37
【问题描述】:

我正在尝试在 VS2012(窗口 7)中运行问题“Understanding ICommand implementation without MVVM”中的代码,但出现错误: “Windows Presentation Foundation (WPF) 项目不支持 AppCommand”

那么,有什么问题或者我应该怎么做才能运行该问题的代码?

MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace seWPFUnderstandingICommandWithout_MVVM
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            AppCommands.AnyCommand.CanExecuteChanged += MyEventHandler;
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            // Nothing for the moment
        }
        private void MyEventHandler(object sender, EventArgs e)
        {
            Console.WriteLine("MyEventHandler called");
        }
     }
     public static class AppCommands
     {
         private static ICommand anyCommand = new MyCommand();

         public static ICommand AnyCommand
         {
             get { return anyCommand; }
         }
     }
     public class MyCommand : ICommand
     {
         bool canExecute;

         public void Execute(object parameter)
         {
            Console.WriteLine("Execute called!");
         }
         public bool CanExecute(object parameter)
         {
             Console.WriteLine("CanExecute called!");
             return CanExecuteResult;
         }
         public event EventHandler CanExecuteChanged;

         public bool CanExecuteResult
         {
             get { return canExecute; }
             set
             {
                 if (canExecute != value)
                 {
                     canExecute = value;
                     var canExecuteChanged = CanExecuteChanged;
                     if (canExecuteChanged != null)
                         canExecuteChanged.Invoke(this, EventArgs.Empty);
                 }
             }
         }
     }
}

【问题讨论】:

    标签: c# wpf mvvm icommand command-pattern


    【解决方案1】:

    如果您的AppCommands 类定义在Namespace.To.AppCommads 命名空间中,您需要在XAML 中声明它:

    xmlns:local="clr-namespace:Namespace.To.AppCommads"
    

    并像这样使用它:

    Command="{x:Static local:AppCommands.AppCommand}"
    

    【讨论】:

    • 并且应该重建项目。没有,它不会赶上 XAML 中的变化
    猜你喜欢
    • 1970-01-01
    • 2012-10-17
    • 2017-08-10
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2016-02-03
    相关资源
    最近更新 更多