gpt4 book ai didi

c# - 理解没有 MVVM 的 ICommand 实现

转载 作者:行者123 更新时间:2023-12-03 10:13:36 25 4
gpt4 key购买 nike

我正在尝试了解如何使用命令。我阅读了很多关于命令的文章,而且我知道,大多数时候命令是在 MVVM 模式中使用的。我还知道,有一个 RoutedCommand 类 - 通常用于在开发时节省时间。

但是 - 我想了解基础知识 - 而这正是问题所在。我们开始吧:

在我的应用程序中,我定义了一个类“MyCommand”:

 public class MyCommand :ICommand
{
public void Execute(object parameter)
{
Console.WriteLine("Execute called!");
CanExecuteChanged(null, null);
}

public bool CanExecute(object parameter)
{
Console.WriteLine("CanExecute called!");
return true;
}

public event EventHandler CanExecuteChanged;
}

好吧——为了获得静态访问,我决定创建一个类,只针对所有应用程序命令:

 public static class AppCommands
{
private static ICommand anyCommand = new MyCommand();

public static ICommand AnyCommand
{
get { return anyCommand; }
}
}

快到了。现在我在主窗口中放置了两个按钮。其中之一“绑定(bind)”到命令:

<StackPanel>
<Button Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" />
<Button Content="Button" Height="23" Name="button2" Width="75" Command="{x:Static local:AppCommands.AnyCommand}" CommandParameter="Hello"/>
</StackPanel>

这是 MainWindow.cs:

public MainWindow()


{
InitializeComponent();
AppCommands.AnyCommand.CanExecuteChanged += MyEventHandler;
}


private void button1_Click(object sender, RoutedEventArgs e)
{
// Nothing for the moment
}

private void MyEventHandler(object sender, EventArgs e)
{
Console.WriteLine("MyEventHandler called");
}

那么 - 让我们运行我的项目。如您所见,我做了一些控制台输出。如果我点击 button2,输出是:

调用了 CanExecute!执行调用!CanExecute 调用!调用了 MyEventHandler

所以,在我看来,这就是发生的事情:1.) 按钮上的命令被“激活”。要检查是否应调用 execute 方法,将调用 CanExecute 方法。2.) 如果 CanExecute 方法返回 true,则调用 Execute 方法。3.) 在执行方法中,我定义了应该引发事件“CanExecuteChanged”。调用它将首先检查“CanExecute”,然后调用事件处理程序。

这个我不是很清楚。调用事件的唯一方法是在 Execute 方法中。但是在检查 CanExecute 之后,通过命令逻辑调用 Execute 方法。调用事件也会检查 CanExecute,但为什么呢?我很困惑。

当我尝试禁用该按钮时,事情变得更加困惑。比方说,有一个“CommandParameter”——“CanExecute”现在可以使用它。因此,该方法可能会返回 false。在这种情况下,按钮被禁用 - 好的。

但是:我该如何重新激活它?我们已经知道:我只能从我的命令类中引发 CanExecuteChange 事件。因此 - 由于我们无法单击禁用按钮 - 该命令不会调用 CanExecute(甚至是 Execute)方法。

在我看来,有一些重要的东西我看不到 - 但我真的找不到它。

你能帮帮我吗?

最佳答案

您的 CanExecuteChanged 不应由 Execute 引发,它应该在 CanExecute 开始返回不同的值时引发。何时取决于您的命令类。在最简单的形式中,您可以添加一个属性:

public class MyCommand : ICommand
{
bool canExecute;

public void Execute(object parameter)
{
Console.WriteLine("Execute called!");
}

public bool CanExecute(object parameter)
{
Console.WriteLine("CanExecute called!");
return CanExecuteResult;
}

public event EventHandler CanExecuteChanged;

public bool CanExecuteResult
{
get { return canExecute; }
set {
if (canExecute != value)
{
canExecute = value;
var canExecuteChanged = CanExecuteChanged;
if (canExecuteChanged != null)
canExecuteChanged.Invoke(this, EventArgs.Empty);
}
}
}
}

关于c# - 理解没有 MVVM 的 ICommand 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10812323/

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