WPF MVVM模式下获取Button的Content

来源:互联网 发布:淘宝淘部落怎么报名 编辑:程序博客网 时间:2024/06/05 08:53

简介:

   MVVM模式下,两个Button使用一个Command事件,并且获取Button的Content

案例:

   Command事件传值

源码:

----------------- View

<Window x:Class="Demo_Mvvm.Views.WindowView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WindowView" Height="300"Width="300">
    <Grid Background="Yellow">
        <Button Height="25"Width="75"Margin="-100,0,0,0"Content="北京"x:Name="BeiJing"
                Command="{Binding ButtonCommand}"CommandParameter="{Binding Content,ElementName=BeiJing}">
        </Button>
        <Button Height="25" Width="75"Margin="100,0,0,0"Content="老黑" x:Name="BlackJason"
                Command="{Binding ButtonCommand}"CommandParameter="{Binding Content,ElementName=BlackJason}">
        </Button>
    </Grid>
</Window>

----------------ViewModel

using System;
using System.Windows;
using System.Threading;
using System.Collections.ObjectModel;
using SimpleMvvmToolkit;

namespace Demo_Mvvm.ViewModels
{
    public class WindowViewModel:ViewModelBase<WindowViewModel>
    {
        public WindowViewModel()
        {
        }
        public DelegateCommand<string> ButtonCommand
        {
            get
            {
                return new DelegateCommand<string>(ButtonWay);
            }
        }
        public void ButtonWay(string buttonContent)
        {
            MessageBox.Show(buttonContent);
        }
    }
}

截图:


    

1 0