WPF单选按钮命令绑定

4
我目前在ViewModel中有一个自定义对象的ObservableCollection。这个集合绑定到视图中的ListBox的ItemsSource属性上,在该视图中,集合中的每个项目都会显示为一个RadioButton。
针对这些单选按钮,我试图让它们在选中时执行继电器命令(假设我应该将RadioButton的Command属性绑定到继电器命令),但我认为这不是正确的实现方式,因为会出现以下错误:
System.Windows.Data Error: 40 :
BindingExpression path error:'SelectCommand' property not found on 'object' ''CustomObject' (HashCode=37826814)'.
BindingExpression:Path=SelectCommand;
DataItem='CustomObject' (HashCode=37826814);
target element is 'RadioButton' (Name='');
target property is 'Command' (type 'ICommand')
这是因为它尝试在CustomObject中查找命令,而不是在ViewModel中查找。如何解决这个问题?
如果您能提供任何帮助,将不胜感激。
1个回答

4
这是因为它试图在CustomObject中查找命令,而不是ViewModel。你需要绑定到具有DataContext设置为你的ViewModel的元素的DataContext。一个好主意是绑定到父ListBox。
{Binding DataContext.SelectCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接