c# - WPF RadioButton 命令绑定(bind)

标签 c# wpf mvvm radio-button command

我目前在我的 ViewModel 中有一个自定义对象的 ObservableCollection。在我看来,此集合绑定(bind)到 ListBox 中的 ItemsSource 属性,其中集合中的每个项目都显示为 RadioButton

使用这些单选按钮,我试图让它们在选中按钮时执行中继命令(假设我应该将 RadioButtonCommand 属性绑定(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/

相关文章:

mvvm - knockout 页面中的多个 View 模型不起作用

c# - 由于 SystemEvents.OnUserPreferenceChanged 事件,WinForms 应用程序挂起

c# - 为什么使用 Caliburn Micro Conductor.OneActive 时,Blend Interaction 事件触发器会多次触发?

c# - 验证从异步调用报告的进度是否在单元测试中正确报告

c# - 网格列和行长度上的 WPF 转换器仅在不使用 gridsplitter 时才有效

c# - WPF DataGrid 在 IsSelected 时设置文本换行

c# - 我想在 MVVM 中使用 ListBox 的 SelectionChangeEvent

silverlight - 如何根据绑定(bind)值更改列表项的视觉样式?

c# - 如何将 C# 代码转换为 C++

c# - 如何获取 IEnumerable 列表值?