我目前在我的 ViewModel 中有一个自定义对象的 ObservableCollection
。在我看来,此集合绑定(bind)到 ListBox
中的 ItemsSource
属性,其中集合中的每个项目都显示为 RadioButton
。
使用这些单选按钮,我试图让它们在选中按钮时执行中继命令(假设我应该将 RadioButton
的 Command
属性绑定(bind)到中继命令),我不认为这是实现此错误的正确方法,因为出现此错误:
- System.Windows.Data 错误:40:
- BindingExpression 路径错误:在“对象”“CustomObject”(HashCode=37826814) 上找不到“SelectCommand”属性。
- 绑定(bind)表达式:Path=SelectCommand;
- DataItem='CustomObject' (HashCode=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?
没错,您需要绑定(bind)到将 DataContext
设置为您的 ViewModel 的元素的 DataContext
。
一个好主意是绑定(bind)到父 ListBox
。
{Binding DataContext.SelectCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}}
关于c# - WPF RadioButton 命令绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31431708/