wpf - 控件模板中的 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();
解决方案
由于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; }
推荐阅读
- x86 - 在将 XGETBV 的结果用于 XSETBV 之前,我应该还是不应该掩盖它们?
- cypress - 赛普拉斯:新的 cy.intercept() 方法是否应该模拟不是从浏览器发送的请求的响应,而是使用 cy.request() 方法?
- reactjs - 如果在输入字段中未进行任何更改,如何禁用提交按钮?
- swift - AFHTTPRequestOperation 的合适替代品是什么?
- jwt - springdoc:如何为请求设置默认的 JWT 令牌(演示 API)?
- powershell - PowerShell 远程处理未安装 MSI
- javascript - 如何使用material-ui动态添加/删除类名?
- swift - 是否有类似于 Java 中的 Reentrant Lock for Swift 的库?
- python - 这个生成器 for 循环的扩展形式是什么?
- android - ArcGIS Android SDK,使用vectorDrawable向mapView添加标记