WPF RadioButton 命令绑定
WPF RadioButton Command binding
目前我的 ViewModel 中有 ObservableCollection
个自定义对象。在我看来,此集合绑定到 ListBox
中的 ItemsSource
属性,其中集合中的每个项目显示为 RadioButton
.
使用这些单选按钮,我试图让它们在选中按钮时执行中继命令(假设我应该将 RadioButton
的 Command
属性 绑定到中继命令),我不认为这是实现此错误的正确方法:
- System.Windows.Data 错误:40:
- BindingExpression 路径错误:'SelectCommand' 属性 在 'object' ''CustomObject' (HashCode=37826814)' 上找不到。
- 绑定表达式:Path=SelectCommand;
- DataItem='CustomObject' (哈希码=37826814);
- 目标元素是 'RadioButton' (Name='');
- 目标 属性 是 'Command'(类型 'ICommand')
这是因为它试图在 CustomObject
中查找命令,而不是在 ViewModel
中查找命令吗?如何解决?
如有任何帮助,我们将不胜感激。
Is this because it is trying to look for the command within the CustomObject, rather than the ViewModel instead?
没错,您需要绑定到 DataContext
设置为 ViewModel 的元素的 DataContext
。
一个好主意是绑定到父级 ListBox
。
{Binding DataContext.SelectCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}}
目前我的 ViewModel 中有 ObservableCollection
个自定义对象。在我看来,此集合绑定到 ListBox
中的 ItemsSource
属性,其中集合中的每个项目显示为 RadioButton
.
使用这些单选按钮,我试图让它们在选中按钮时执行中继命令(假设我应该将 RadioButton
的 Command
属性 绑定到中继命令),我不认为这是实现此错误的正确方法:
- System.Windows.Data 错误:40:
- BindingExpression 路径错误:'SelectCommand' 属性 在 'object' ''CustomObject' (HashCode=37826814)' 上找不到。
- 绑定表达式:Path=SelectCommand;
- DataItem='CustomObject' (哈希码=37826814);
- 目标元素是 'RadioButton' (Name='');
- 目标 属性 是 'Command'(类型 'ICommand')
这是因为它试图在 CustomObject
中查找命令,而不是在 ViewModel
中查找命令吗?如何解决?
如有任何帮助,我们将不胜感激。
Is this because it is trying to look for the command within the CustomObject, rather than the ViewModel instead?
没错,您需要绑定到 DataContext
设置为 ViewModel 的元素的 DataContext
。
一个好主意是绑定到父级 ListBox
。
{Binding DataContext.SelectCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}}