MVVMLight View to ViewModel 消息传递

设想的场景是这样的:点击一个按钮,弹出一个 MessageBox 消息框,用户选择 Yes 才执行下一步的操作。

MVVMLight View to ViewModel 消息传递

XAML:

<Grid DataContext="{Binding Source={StaticResource Locator}, Path=Main}">
    <StackPanel  VerticalAlignment="Center" HorizontalAlignment="Center">
        <StackPanel Orientation="Horizontal"  Margin="10" >
            <TextBlock Text="计算:" VerticalAlignment="Center"/>
            <TextBox Text="{Binding A}" VerticalAlignment="Center"/>
            <TextBlock Text="+" VerticalAlignment="Center"/>
            <TextBox Text="{Binding B}" VerticalAlignment="Center" />
            <TextBlock Text=" = " VerticalAlignment="Center"/>
            <TextBox Text="{Binding C}" Width="50" VerticalAlignment="Center"/>

            <Button x:Name="do_cal" Click="Do_cal_Click" Content="计算" Height="30" Width="80"  Margin="30"/>
        </StackPanel>
    </StackPanel>
</Grid>

CodeBehind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Do_cal_Click(object sender, RoutedEventArgs e)
    {
        Messenger.Default.Send<bool>(MessageBoxResult.Yes ==
            MessageBox.Show("请选择是否进行计算?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Information), "do_cal");
    }
}

MainViewModel:

public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {        
        Messenger.Default.Register<bool>(this, "do_cal", b => Add(b));
    }

    private int _a = 10;
    public int A
    {
        get { return _a; }
        set { _a = value; RaisePropertyChanged(nameof(A)); }
    }

    private int _b = 20;
    public int B
    {
        get { return _b; }
        set { _b = value; RaisePropertyChanged(nameof(B)); }
    }

    private int _c;
    public int C
    {
        get { return _c; }
        set { _c = value; RaisePropertyChanged(nameof(C)); }
    }

    private void Add(bool canDo)
    {
        if (!canDo)
            return;

        C = A + B;
    }
}

消息传递和委托的用法差不多。

MVVMLight View to ViewModel 消息传递

上一篇:Hash的底层原理


下一篇:Simpy BoundClass