【问题标题】:Bind to CheckBox Click event with in WPF MVVM在 WPF MVVM 中绑定到 CheckBox Click 事件
【发布时间】:2020-08-14 21:14:54
【问题描述】:

我正在使用 Caliburn.Micro 编写 WPF 应用程序。我想根据带有复选框的列表框中的选中项目更新名称列表。

XAML:

<ListBox ItemsSource="{Binding Names}">
    <ListBox.ItemTemplate>
        <HierarchicalDataTemplate>
            <CheckBox Content="{Binding Value}" IsChecked="{Binding IsChecked}" />
        </HierarchicalDataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

IsChecked 绑定有效,因此我可以运行一个方法来验证哪些元素已被检查并更新名称列表。我的第一种方法是将命令绑定到复选框 Click 事件或 Checked/Unchecked,但我无法让它工作......

<CheckBox Content="{Binding Value}" IsChecked="{Binding IsChecked}" Click="{Binding UpdateNameList}" />

在我的 ViewModel 中:

public void UpdateNameList()
{
    // update list...
}

我在运行时收到此错误:

error Unable to cast object of type 'System.Reflection.RuntimeEventInfo' to type 'System.Reflection.MethodInfo'.

如何使用 Caliburn.Micro 绑定到复选框单击事件?或者我应该以其他方式做到这一点?

谢谢

【问题讨论】:

  • 如何在 XAML 代码中传递对象和 RoutedEventArgs?

标签: c# wpf caliburn.micro


【解决方案1】:

使用Action.TargetWithoutContext 附加属性将Action.Target 绑定到父视图模型,并使用Message.Attach 连接该方法。这应该有效:

<CheckBox Content="{Binding Value}" IsChecked="{Binding IsChecked}"
        cal:Action.TargetWithoutContext="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListBox}}"
        cal:Message.Attach="UpdateNameList()" />

【讨论】:

  • 太棒了!非常感谢!
猜你喜欢
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 2013-07-26
  • 2014-09-01
  • 1970-01-01
  • 2011-09-23
相关资源
最近更新 更多