XAML:
<Grid DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<StackPanel Orientation="Horizontal" Margin="10" >
<Button x:Name="do_cal" Command="{Binding SendCommand}" Content="计算" Height="30" Width="80" Margin="30"/>
</StackPanel>
</StackPanel>
</Grid>
CodeBehind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Messenger.Default.Register<string>(this, "showMessage", s => ShowMessage(s));
Unloaded += (sender, e) => Messenger.Default.Unregister(this); // 卸载 注册的消息
}
private void ShowMessage(string msg)
{
MessageBox.Show(msg, "消息", MessageBoxButton.YesNo, MessageBoxImage.Information);
}
}
ViewModel:
private RelayCommand sendCommand;
public RelayCommand SendCommand
{
get
{
if (sendCommand == null)
{
sendCommand = new RelayCommand(() => ExcuteSendCommand());
}
return sendCommand;
}
set
{
sendCommand = value;
}
}
private void ExcuteSendCommand()
{
Messenger.Default.Send<string>("来自 ViewModel 的消息!!", "showMessage");
}
MVVMLight ViewModel to View 消息传递
原文:https://www.cnblogs.com/huvjie/p/15041438.html