命令创建方式
方式一:
public DelegateCommand GetTextCommnd { get; set; }
public MainWindowViewModel()
{
this.GetTextCommnd = new DelegateCommand(new Action(ExecuteGetTextCommnd));
}
void ExecuteGetTextCommnd()
{
System.Windows.MessageBox.Show(Obj.Text);
}
方式二:
public DelegateCommand<Button> LoginCommand
{
get
{
return new DelegateCommand<Button>((p) =>
{
});
}
}
方式三:
private DelegateCommand _getTextCommnd;
public DelegateCommand GetTextCommnd => _getTextCommnd ?? (_getTextCommnd = new DelegateCommand(ExecuteGetTextCommnd));
void ExecuteGetTextCommnd()
{
System.Windows.MessageBox.Show(Obj.Text);
}
项目结构:

Model 类
using Prism.Mvvm;
namespace WpfPrism.Models
{
public class MainWindowModel : BindableBase
{
private string _text;
public string Text
{
get { return _text; }
set { SetProperty(ref _text, value); }
}
}
}
ViewModel 类
using System;
using Prism.Commands;
using Prism.Mvvm;
using WpfPrism.Models;
namespace WpfPrism.ViewModels
{
public class MainWindowViewModel : BindableBase
{
public MainWindowViewModel()
{
Obj = new MainWindowModel();
Obj.Text = "默认值";
}
public MainWindowModel Obj { set; get; }
private DelegateCommand _setTextCommnd;
public DelegateCommand SetTextCommnd =>
_setTextCommnd ?? (_setTextCommnd = new DelegateCommand(ExecuteSetTextCommnd));
void ExecuteSetTextCommnd()
{
Obj.Text = "已赋新值";
}
private DelegateCommand _getTextCommnd;
public DelegateCommand GetTextCommnd =>
_getTextCommnd ?? (_getTextCommnd = new DelegateCommand(ExecuteGetTextCommnd));
void ExecuteGetTextCommnd()
{
System.Windows.MessageBox.Show(Obj.Text);
}
}
}
前端 XAML
<Grid>
<StackPanel>
<TextBox Text="{Binding Obj.Text}" Margin="10" Height="100" FontSize="50"/>
<Button Height="100" Width="300" Content="赋值" FontSize="50" Command="{Binding SetTextCommnd}" Margin="10"/>
<Button Height="100" Width="300" Content="取值" FontSize="50" Command="{Binding GetTextCommnd}"/>
</StackPanel>
</Grid>
后台 CS
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}

原文:https://www.cnblogs.com/microsoft-zh/p/14945850.html