MVVMLight ViewModel to View 消息传递

MVVMLight ViewModel to View 消息传递

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 消息传递

上一篇:ArrayList源码


下一篇:Odoo ORM研究2 - BaseModel中的常用方法分析