WPF 通过MVVM绑定自定义命令

WPF 通过MVVM绑定自定义命令

运行示例:
在文本框中输入内容,点击显示内容按钮,弹出MessageBox显示输入的内容;
在这里插入图片描述
选择combobox中的内容,弹出MessageBox显示combobox中选择的内容;
在这里插入图片描述
代码:
一.使用自定义MVVM框架:
在NuGet包中下载interactivity(为了combobox控件绑定自定义命令)
添加一个MyCommand文件夹,在其中添加一个类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfApplication3.MyCommand
{
    class DelegateCommand : ICommand
    {
        public bool CanExecute(object parameter)
        {
            if (CanExecuteFunc == null)
                return true;
            return this.CanExecuteFunc(parameter);
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (ExecuteAction == null)
            {
                return;
            }
            this.ExecuteAction(parameter);
        }
        public Action<object> ExecuteAction { get; set; }
        public Func<object, bool> CanExecuteFunc { get; set; }
    }
}

然后添加一个文件夹MyViewModels,其中添加两个类:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication3.ViewModels
{
    class NotificationObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WpfApplication3.MyCommand;

namespace WpfApplication3.ViewModels
{
    class MainWindowViewModel : NotificationObject
    {
        public MainWindowViewModel()
        {
            this.Test001_Command = new DelegateCommand();
            this.Test001_Command.ExecuteAction = new Action<object>(this.Test001_Function);

            this.Test002_Command = new DelegateCommand();
            this.Test002_Command.ExecuteAction = new Action<object>(this.Test002_Function);
        }


        public DelegateCommand Test001_Command { get; set; }

        private void Test001_Function(object parameter)
        {
            string str = parameter.ToString();
            MessageBox.Show(str);
        }


        public DelegateCommand Test002_Command { get; set; }

        private void Test002_Function(object parameter)
        {
            string str = parameter.ToString();
            MessageBox.Show(str);
        }
    }
}

主窗体XAML代码:

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        Title="MainWindow1" Height="350" Width="300">
    <Grid>
        <StackPanel>
            <TextBlock Margin="10 30 10 0" Text="请输入内容..."></TextBlock>
            <TextBox Margin="10" Name="tbMsg"></TextBox>
            <Button Margin="10" Content="显示内容" Name="btnSet" Command="{Binding Test001_Command}" CommandParameter="{Binding ElementName=tbMsg, Path=Text}"></Button>
            <ComboBox Margin="10" Name="comobox1">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="DropDownClosed">
                        <i:InvokeCommandAction Command="{Binding Test002_Command}" CommandParameter="{Binding ElementName=comobox1,Path=Text}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
                <TextBlock>one</TextBlock>
                <TextBlock>two</TextBlock>
                <TextBlock>three</TextBlock>
            </ComboBox>
        </StackPanel>
    </Grid>
</Window>

主窗体后台代码:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }
    }

二.使用MVVM Light框架(使用NuGet下载MVVM Light,会自动生成一个ViewModel文件夹,我们只保留其中的一个类MainViewModel即可)
MainViewModel类代码:

using GalaSoft.MvvmLight;
using System.Windows;

namespace WpfApp1.ViewModel
{

    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            Test001_Command = new GalaSoft.MvvmLight.Command.RelayCommand<object>(Test001_Function);

            Test002_Command = new GalaSoft.MvvmLight.Command.RelayCommand<object>(Test002_Function);
        }

        public GalaSoft.MvvmLight.Command.RelayCommand<object> Test001_Command { get; set; }

        public void Test001_Function(object parameter)
        {
            string str = parameter.ToString();
            MessageBox.Show(str);
        }

        public GalaSoft.MvvmLight.Command.RelayCommand<object> Test002_Command { get; set; }

        public void Test002_Function(object parameter)
        {
            string str = parameter.ToString();
            MessageBox.Show(str);
        }
    }
}

主窗体XAML代码:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow2" Height="450" Width="300">
    <Grid>
        <StackPanel>
            <TextBlock Margin="10 30 10 0" Text="请输入内容..."></TextBlock>
            <TextBox Margin="10" Name="tbMsg"></TextBox>
            <Button Margin="10" Content="显示内容" Name="btnSet" Command="{Binding Test001_Command}" CommandParameter="{Binding ElementName=tbMsg, Path=Text}"></Button>
            <ComboBox Margin="10" Name="comobox1">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="DropDownClosed">
                        <i:InvokeCommandAction Command="{Binding Test002_Command}" CommandParameter="{Binding ElementName=comobox1,Path=Text}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
                <TextBlock>one</TextBlock>
                <TextBlock>two</TextBlock>
                <TextBlock>three</TextBlock>
            </ComboBox>
        </StackPanel>
    </Grid>
</Window>

主窗体后台代码:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值