1. 程式人生 > >WPF MVVM模式下獲取Button的Content

WPF MVVM模式下獲取Button的Content

簡介:

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

截圖: