gpt4 book ai didi

c# - 如何在 ListView 的 SelectionChanged 上调用 ViewModel 上的命令?

转载 作者:行者123 更新时间:2023-11-30 15:00:36 25 4
gpt4 key购买 nike

在 MVVM/WPF 环境中,我想在引发 ListView 的 SelectionChanged 事件时在 ViewModel 上调用命令 (ComputeCommand)。如何在 XAML 或 C# 中完成此操作?

这是我的命令类。我在代码隐藏中尝试了 MainViewModel.Instance.MyCommand.Execute();,但它不接受。

public class ComputeCommand : ICommand
{
public ComputeCommand(Action updateReport)
{
_executeMethod = updateReport;
}

Action _executeMethod;

public bool CanExecute(object parameter)
{
return true;
}

public event EventHandler CanExecuteChanged;

public void Execute(object parameter)
{
_executeMethod.Invoke();
}
}

最佳答案

我真的推荐使用像MVVM Light 这样的Mvvm 框架。 ,所以你可以这样做:

XAML:

xmlns:MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"
xmlns:Custom="clr-namespace:System.Windows.Interactivity; assembly=System.Windows.Interactivity"

<ListBox>
...
<Custom:Interaction.Triggers>
<Custom:EventTrigger EventName="SelectionChanged ">
<MvvmLight_Command:EventToCommand PassEventArgsToCommand="False" Command="{Binding Path=ComputeCommand}"/>
</Custom:EventTrigger>
</Custom:Interaction.Triggers>

</Listbox>

View 模型:

public RelayCommand ComputeCommand{ get; private set; }

在我看来,这是一种让您的事件布线干净整洁的优雅方式。

关于c# - 如何在 ListView 的 SelectionChanged 上调用 ViewModel 上的命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15267031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com