首页 > 其他分享 >WPF 命令Command

WPF 命令Command

时间:2024-08-16 18:06:25浏览次数:7  
标签:MyCom object 命令 Command new WPF public

MVVM的目的是为了最大限度地降低了Xaml文件和CS文件的合度,分离界面和业务逻辑,所以我们要尽可能的在View后台不写代码。
但是这个例子中,我们将更新ViewModel的代码写在了View里。我们能否把按钮的响应处理代码也不写在后台代码里呢? WPF引入Command(命令),通过为Button设置Command来做响应: 命令:Command是一种不同于输入设备的语义级别上的入处理机制 Command的目的:1)降低代码耦合度,将Command的逻辑和调用对象进行分离2)可以指定对象是否可用;Command允许多个不同的对象可以调用同一个命令,也可以为不同的对象定义特殊的逻辑;
命令分类:
1.预定义的命令(predefined command)
1)ApplicationCommands 提供一组与应用程序相关的标准命令(可以直接使用
2)ComponentCommands 提供一组标准的与组件相关的命令
3)Navigationcommands,提供一-组标准的与导航相关的命令
还有很多诸如:MediaCommands,EditingCommands 2.自定义Command (1)command:要执行的操作。 所有的命令需要继承自接口ICommand. Execute:执行与命令关联的操作, CanExecute:决定对于当前目标command能否被执行。 CanExecuteChanged(事件):当出现影响是否应执行该命令的更改时发生
public class RelayCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;
        private Action<object> executeActions;
        private Func<object, bool> canExecuteFunc;
        public RelayCommand() { }
        public RelayCommand(Action<object> execute) : this(execute, null)
        {

        }
        public RelayCommand(Action<object> execute, Func<object, bool> canExecute)
        {
            this.executeActions = execute; 
            this.canExecuteFunc = canExecute;
        }
        public bool CanExecute(object parameter)
        {
            if (canExecuteFunc != null)
                return this.canExecuteFunc(parameter);
            else
                return true;
        }

        public void Execute(object parameter)
        {
            if (executeActions == null) 
                return; 
            this.executeActions(parameter);
        }
        public void OnCanExecutechanged()
        {
            this.CanExecuteChanged?.Invoke(this, new EventArgs());
        }
    }
二、建立业务类 MainViewModel类
    public class MainViewModel
    {
        //先实例化这个命令(这是属于ViewModel的命令,等下要被送到View中去)
        public RelayCommand MyCom { get; set; }public MainViewModel()
        {
            //在ViewModel的构造函数中,完成对命令的设置
            MyCom = new RelayCommand();
            MyCom.canExecuteFunc = new Func<object, bool>(this.CanDoSomething);//命令执行先进行判断,这里和MyCommand中的CanExecute都可以进行判断。
            MyCom.executeActions = new Action<object>(this.DoSomething);//执行命令,带一个参数
                                                                        //MyCom.ExecuteAction0 = new Action(this.DoSomething0);//执行命令,不带参数

        }

        public void DoSomething(object param)
        {
            MessageBox.Show("123" + param);//执行方法,返回界面的命令带的参数
        }

        public void DoSomething0()
        {
            MessageBox.Show("123");//执行方法,返回界面的命令带的参数
        }
        public bool CanDoSomething(object param)
        {
            //这里可以和界面进行数据交互,进行判断。判断能否做这个事情,大部分时候返回true就行了,返回false,方法就不执行了。
            return true;
        }
    }
3.在MainWindow中关联上MainViewModel。
 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }
    }
<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:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="222,185,0,0" Command="{Binding MyCom}" CommandParameter="{Binding ElementName=txt, Path=Text}" VerticalAlignment="Top" Width="75"/>
        <TextBox x:Name="txt" HorizontalAlignment="Left" Height="23" Margin="222,128,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
 
    </Grid>
</Window>
上面是传递单个值,下面说说多值传递的问题,传值有2种方法

第一种,建立一个对象,把对象当做整体传入

首先建立stu类

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
  public int Gender { get; set; }
  public double Left { get; set; }
  public double Top { get; set; }
}

public class MainViewModel
    {
        //先实例化这个命令(这是属于ViewModel的命令,等下要被送到View中去)
        public RelayCommand MyCom { get; set; }
        public Person person { get; set; }
        public MainViewModel()
        {
            //在ViewModel的构造函数中,完成对命令的设置
            MyCom = new RelayCommand();
            MyCom.canExecuteFunc = new Func<object, bool>(this.CanDoSomething);//命令执行先进行判断,这里和MyCommand中的CanExecute都可以进行判断。
            MyCom.executeActions = new Action<object>(this.DoSomething);//执行命令,带一个参数
                                                                        //MyCom.ExecuteAction0 = new Action(this.DoSomething0);//执行命令,不带参数
            person = new Person() { Name = "aaa", Age = 3 };
        }

        public void DoSomething(object param)
        {
            MessageBox.Show("123" + param);//执行方法,返回界面的命令带的参数
        }

        public void DoSomething0()
        {
            MessageBox.Show("123");//执行方法,返回界面的命令带的参数
        }
        public bool CanDoSomething(object param)
        {
            //这里可以和界面进行数据交互,进行判断。判断能否做这个事情,大部分时候返回true就行了,返回false,方法就不执行了。
            return true;
        }
    }
第二种,使用多参数的方式传值 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
 
namespace WpfApp1
{
    public class ObjectConvert : IMultiValueConverter
    {
        #region IMultiValueConverter Members
 
        public static object ConverterObject;
 
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
 
            return values.ToArray();
        }
 
        public object[] ConvertBack(object value, Type[] targetTypes,
          object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
 
        #endregion
    }
}


<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:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:ObjectConvert x:Key="objectConverter"></local:ObjectConvert>
    </Window.Resources>
        <Grid>
        <!--<Button Content="Button" HorizontalAlignment="Left" Margin="222,185,0,0" Command="{Binding MyCom}" CommandParameter="{Binding ElementName=txt, Path=Text}" VerticalAlignment="Top" Width="75"/>-->
        <!--<Button Content="Button" HorizontalAlignment="Left" Margin="222,185,0,0" Command="{Binding MyCom}" CommandParameter="{Binding a}" VerticalAlignment="Top" Width="75"/>-->
        <Button Content="Button" HorizontalAlignment="Left" Margin="222,185,0,0" Command="{Binding MyCom}"  VerticalAlignment="Top" Width="75">
            <Button.CommandParameter>
                <MultiBinding Converter="{ StaticResource ResourceKey=objectConverter}">
                    <Binding ElementName="txt"></Binding><!--传整个控件-->
                    <Binding ElementName="txt_Copy" Path="Text"></Binding><!--传控件的值-->
                    <Binding Path="a" ></Binding><!--传对象-->
                    <Binding Source="自定义值"   ></Binding> <!--传自定义的值-->
                </MultiBinding>
            </Button.CommandParameter>
        </Button>
        <TextBox x:Name="txt" HorizontalAlignment="Left" Height="23" Margin="222,128,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="txt_Copy" HorizontalAlignment="Left" Height="23" Margin="412,172,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
 
    </Grid>
</Window>

 

 
来源:https://blog.csdn.net/u012563853/article/details/124892976

 

标签:MyCom,object,命令,Command,new,WPF,public
From: https://www.cnblogs.com/ywtssydm/p/18362435

相关文章

  • WPF 绑定
    绑定就是Binding,是控件和数据之间交互的类。source={binding}和source={bindingRelativeSource={RelativeSourceself},Path=DataContext}效果相同。例如:直接绑定数据源前台xaml界面<Grid><StackPanelOrientation="Vertical"><TextBlock......
  • Git 命令大全:详细讲解与常见问题解决方案
    目录1.Git基础命令2.分支管理命令3.远程仓库管理命令4.标签管理命令5.其他常用命令6.总结Git是目前最流行的分布式版本控制系统,它使得团队协作和代码管理变得更加高效。本文将详细介绍Git的常用命令及其应用场景,并针对可能遇到的问题提供解决方案。1.Git......
  • minikube && k8s 命令
    minikubedocker-envminikubedashboardminikubessh导出一个已经创建的容器导到一个文件dockerexport-o文件名.tar容器id将文件导入为镜像dockerimport文件名.tar镜像名:镜像标签本地镜像关联到minikubeminikube"docker-env"将容器保存为镜像:dockercommit<容......
  • WPF Animation 动画变化值的监控
    WPF动画XXXAnimation即关键类继承制AnimationBase的动画类线性插值动画主要属性FromToDurationAcceleratorDecceleratorFillBehavior等这些常用属性里不做介绍,主要介绍一下几个故事板属性,以备忘记.名称说明Completed动画到达终点时触发,该事件中可以......
  • git command 工作中常用命令备忘录
    模拟目前工作流程在gitlabfork需要开发的项目到自己仓库分配一个工作任务(feature、improvment、bug)本地从个人仓库克隆项目gitclonehttp://mylocal/group/project本地添加对于远端项目gitremoteaddupstreamhttp://dev.xxx.io/group/project基于远端仓库切出本......
  • WPF 触发器
    一、样式触发器样式触发器可以在指定的控件属性满足某种条件后进行一些样式的变换,当触发条件不满足时恢复原样。样式触发器的简单使用<Window.Resources><Stylex:Key="checkBoxStyle"TargetType="CheckBox"><Style.Triggers><TriggerProperty="......
  • 【Linux操作系统】——Linux基本命令3
    1、vi与vim的简介  在Linux下,绝大部分的配置文件都是以ASCII码的纯文本形式存在的,可以利用一些简单的编辑软件修改配置。  在Linux命令行界面下的文本编辑器有很多,比如nano,Emacs,vim等。但是所有的UNIXLike系统都会内置vi文本编辑器,而其他的文本编辑器则不一定存在......
  • PHP命令执行与绕过
    一、eval()函数调用--无严格过滤:1、highlight_file()高亮显示:?c=highlight_file(base64_decode("ZmxhZy5waHA="));2、shell命令:?c=system("tacfl*g.php");?c=system("catfl*g.php");3、echo直接打印:(使用反引号包裹shell命令)?c=echo'tacfla*.php';4、......
  • 在Windows系统打开开始菜单,输入cmd 命令打开命令提示符
    ftp>pwd#匿名访问ftp的根目录为Linux系统的/var/ftp/目录ftp>ls#查看当前目录ftp>cdpub#切换到pub目录ftp>get文件名#下载文件到当前Windows本地目录ftp>lsftp>gettest.txt#获取目录中的文件下载到电脑ftp>lsftp>puttest4.txt......
  • WPF 窗体关闭的方式
    1.Close();关闭当前窗口在WPF应用程序的关闭是有ShutdownMode属性设置,具有3中枚举类型的值:1)OnLastWindowClose(默认值)---应用程序最后一个窗体关闭时关闭应用程序2)OnMainWindowClose---应用程序主窗体关闭时关闭应用程序3)OnxplicitShutdown---显示调用关闭这......