首页 > 其他 > 详细

MVVMLight ViewModel to View 消息传递

时间:2021-07-21 23:15:27      阅读:47      评论:0      收藏:0      [点我收藏+]

技术分享图片

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");
}



参考: https://www.cnblogs.com/wzh2010/p/6679025.html

MVVMLight ViewModel to View 消息传递

原文:https://www.cnblogs.com/huvjie/p/15041438.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!