我有一个来自Telerik的自定义控件模板,Ive向其中添加了一个(拆分)按钮。如何将命令处理程序绑定到它?我试图在公共类中添加公共静态命令使用诸如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。
我已经尝试过在视图模型和类pf中定义命令(请参见下文)(我使用Prism(因此使用Delegate命令,但只要它可以工作,就不必是Delegate命令)]
//public static RoutedUICommand ShowSearchCommand = new RoutedUICommand("ShowSearchCommand", "ShowSearchCommand", typeof(TabbedWindowCommands));
//public static DelegateCommand ShowSearchCommand = new DelegateCommand();
由于ShowSearchCommand
不是RadSplitButton
本身的属性,而是DataContext
的属性,因此应在绑定路径中包括DataContext
:
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type telerik:RadSplitButton}}, Path=DataContext.ShowSearchCommand}" Margin="2" />
您可能还希望根据AncestorType
的位置和设置方式将Window
更改为DataContext
。
还请注意,您只能绑定到公共属性,这意味着ShowSearchCommand
必须是属性而不是字段:
public DelegateCommand ShowSearchCommand { get; }