Command详细使用🔥
CZerocheng 1/4/2024 MVVMCommunityToolkit
# 基础用法
本次使用CommunityTookit和HandyControl工具实现MVVM,先创建一个你想要的ViewModel,名为CommandTestViewModel,里面定义了一个GreetUserCommand。
public class CommandTestViewModel
{
public IRelayCommand greetUserCommand { get; set; }
public IRelayCommand GreetUserCommand => greetUserCommand ??= new RelayCommand(GreetUser);
public void GreetUser()
{
MessageBox.Show($"Hello Command!");
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
在xaml文件里面实现上下文的绑定
<UserControl.DataContext>
<viewmodel:CommandTestViewModel />
</UserControl.DataContext>
1
2
3
2
3
接着编写一个Button
<Button Command="{Binding GreetUserCommand}"/>
1
即可实现按钮与ViewModel中的GreetUserCommand的绑定。
# 特性用法
需要在
public class CommandTestViewModel
1
中加上partial变成
public partial class CommandTestViewModel
1
在你想要绑定的方法上面加上[RelayCommand]这个特性
public partial class CommandTestViewModel
{
[RelayCommand]
public void GreetUser()
{
MessageBox.Show($"Hello Command!");
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
在xaml文件里面绑定GreetUserCommand,记得后面要加Command
<Button Command="{Binding GreetUserCommand}"/>
1
即可实现用特性绑定命令。
# 异步命令
如果你的操作是比较耗时的,但是你又不想把界面卡住,这时你可以使用IAsyncRelayCommand,使用如下:
private IAsyncRelayCommand getTextCommond { get; set; }
public IAsyncRelayCommand GetTextCommond => getTextCommond ??= new AsyncRelayCommand(GetText);
public async Task GetText()
{
await Task.Delay(5000);
MessageBox.Show("Test");
}
1
2
3
4
5
6
7
2
3
4
5
6
7
如果按照IRelayCommand的写法,同样的代码,你是会把界面卡住的。