【问题标题】:CommandConverter cannot convert from System.String in WPFCommandConverter 无法从 WPF 中的 System.String 转换
【发布时间】:2014-04-12 17:11:38
【问题描述】:

我在使用 .NET Framework 4.5 的 WPF 中遇到奇怪的错误

<Window.CommandBindings>
        <CommandBinding Command="ImportExcelCmd" CanExecute="ImportExcelCmd_CanExecute" Executed="ImportExcelCmd_Executed"></CommandBinding>
</Window.CommandBindings>
<Window.InputBindings>
        <KeyBinding Key="I" Modifiers="Control" Command="ImportExcelCmd"></KeyBinding>
</Window.InputBindings>

我收到CommandConverter cannot convert from System.String 的错误

我的错误在哪里?

我有另一个与 ListView 的绑定,例如:

<ListView.CommandBindings>
     <CommandBinding Command="Delete" CanExecute="Delete_CanExecute" Executed="Delete_Executed"></CommandBinding>
</ListView.CommandBindings>
<ListView.InputBindings>
      <KeyBinding Key="Delete" Command="Delete"></KeyBinding>
</ListView.InputBindings>

它有效。

【问题讨论】:

  • Delete 用于以下上下文:&lt;Button Command="Delete"&gt;&lt;/Button&gt;。现在我有 ImportExcelCmd 的问题
  • 为什么不将命令绑定到您的视图模型?
  • 现在我明白创建自定义命令了。

标签: c# wpf


【解决方案1】:

如果你想使用Custom Routed commands,你可以使用更详细的定义。

在类中将路由命令声明为static,然后在XAML 中使用x:Static 使用它。 可以参考答案here


为了回答的完整性,我把答案中的相关代码贴在这里:

namespace MyApp.Commands
{
    public class MyApplicationCommands
    {
        public static RoutedUICommand ImportExcelCmd 
                            = new RoutedUICommand("Import excel command", 
                                                  "ImportExcelCmd", 
                                                  typeof(MyApplicationCommands));
    }
}

XAML

<Window x:Class="..."
             ...
             xmlns:commands="clr-namespace:MyApp.Commands">
...
<Window.CommandBindings>
    <CommandBinding
            Command="{x:Static commands:MyApplicationCommands.ImportExcelCmd}"
            CanExecute="ImportExcelCmd_CanExecute"
            Executed="ImportExcelCmd_Executed" />
</Window.CommandBindings>

【讨论】:

  • 那为什么使用“DElete”命令有效而“ImportExcelCmd”无效?好的,我必须创建自定义绑定。
  • Delete 有效,因为这是默认的应用程序命令,而不是自定义命令。对于您使用的自定义命令,就像我在回答中提到的那样。
  • 还有一个问题。在ImportExcelCmd_CanExecute 上,如果我输入e.CanExecute = true;,那么ImportExcelCmd_CanExecute 方法会执行两次......为什么?
  • 理想情况下CanExecute 应该只包含检查命令是否可以执行的条件。如果您要添加一些额外的代码,请不要这样做。其次,命令管理器在内部检查命令是否可以执行。因此,只要命令管理器想查看命令是否可以执行,它就会被调用。
  • 你在哪里实现ImportExcelCmd_CanExecute?在窗口的代码隐藏文件中?
猜你喜欢
  • 2012-01-26
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 2015-07-09
相关资源
最近更新 更多