首页 > 解决方案 > 控件模板中的 WPF 命令 - >“CommandConverter 无法从 > System.String 转换。”

问题描述

我有一个来自 Telerik 的自定义控件模板,并且我在其中添加了一个(拆分)按钮。如何将命令处理程序绑定到它?我试图在公共类中添加一个公共静态命令,以使用诸如 x:static ns:Class.Command 之类的绑定以及各种变体(如下所示)和大多数 SO-命中。

<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:RadSplitButton}}, Path=ShowSearchCommand}" Margin="2" />

<Button Content="Click me" Command="{x:Static vm:MainWindowViewModel.ShowSearchCommand}" CommandParameter="one"/>

它们都以错误消息结尾

NotSupportedException:CommandConverter 无法从 System.String 转换。

我已经尝试在视图模型和它自己的类中定义命令(见下文)(我正在使用 Prism(因此是委托命令,但它不必是委托命令,只要它有效)

  //public static RoutedUICommand ShowSearchCommand = new RoutedUICommand("ShowSearchCommand", "ShowSearchCommand", typeof(TabbedWindowCommands));


//public static DelegateCommand ShowSearchCommand = new DelegateCommand();

标签: wpftelerik

解决方案


由于ShowSearchCommand不是RadSplitButton自身 的 属性 而是 其的 属性,因此DataContext您应该DataContext在绑定路径中包含:

<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, 
    AncestorType={x:Type telerik:RadSplitButton}}, Path=DataContext.ShowSearchCommand}" Margin="2" />

您可能还想根据设置的位置和方式将 更改AncestorType为。WindowDataContext

另请注意,您只能绑定到公共属性,这意味着它ShowSearchCommand必须是属性而不是字段:

public DelegateCommand ShowSearchCommand { get; }

推荐阅读