利用System.Windows.Interactivity.dll实现View时间在ViewModel中处理(可带sender、EventArgs参数)...

本文介绍了一种在WPF中扩展命令执行方式的方法,通过自定义`ExtendedInvokeCommandAction`类来增强命令参数传递的功能,并展示了如何在View层绑定此命令行动作。

一、公共类
namespace Gh.Ticket.Common

{

    public class ExtendedCommandParameter

    {

        public ExtendedCommandParameter(EventArgs eventArgs, FrameworkElement sender, object parameter)

        {

            EventArgs = eventArgs;

            Sender = sender;

            Parameter = parameter;

        }

        public EventArgs EventArgs { getprivate set; }

        public FrameworkElement Sender { getprivate set; }

        public object Parameter { getprivate set; }

    }

    public class ExtendedInvokeCommandAction : TriggerAction<FrameworkElement>

    {

        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command"typeof(ICommand), typeof(ExtendedInvokeCommandAction), new PropertyMetadata(null, CommandChangedCallback));

        public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter"typeof(object), typeof(ExtendedInvokeCommandAction), new PropertyMetadata(null, CommandParameterChangedCallback));

        private static void CommandParameterChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            var invokeCommand = d as ExtendedInvokeCommandAction;

            if (invokeCommand != null)

                invokeCommand.SetValue(CommandParameterProperty, e.NewValue);

        }

        private static void CommandChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            var invokeCommand = d as ExtendedInvokeCommandAction;

            if (invokeCommand != null)

                invokeCommand.SetValue(CommandProperty, e.NewValue);

        }

        protected override void Invoke(object parameter)

        {

            if (this.Command == null)

                return;

            if (this.Command.CanExecute(parameter))

            {

                var commandParameter = new ExtendedCommandParameter(parameter as EventArgsthis.AssociatedObject,

                                                                    GetValue(CommandParameterProperty));

                this.Command.Execute(commandParameter);

            }

        }

        #region public properties

        public object CommandParameter

        {

            get { return GetValue(CommandParameterProperty); }

            set { SetValue(CommandParameterProperty, value); }

        }

        public ICommand Command

        {

            get { return GetValue(CommandProperty) as ICommand; }

            set { SetValue(CommandParameterProperty, value); }

        }

        #endregion

    }

}

二、View

 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

 xmlns:local="ExtendedInvokeCommandAction类所在命名空间"

  <TextBox x:Name="txtControlID"  >

                        <i:Interaction.Triggers>

                            <i:EventTrigger EventName="PreviewKeyDown">

                                <local:ExtendedInvokeCommandAction

                                        Command="{Binding CustomCommand}"

                                        //这里不绑定则ExtendedCommandParameter.Parameter的值为对应ViewModel的值,否则可绑定其他控件的属性值

                                        CommandParameter="{Binding}"

                                />

                            </i:EventTrigger>

                        </i:Interaction.Triggers>

                    </TextBox>

三、ViewMode
 public ICommand CustomCommand

        {

            get

            {

                return new DelegateCommand<object>(x =>

                    {

                        ExtendedCommandParameter p = x as ExtendedCommandParameter;

                         p.sender  触发事件对象

                         p.EventArgs 事件参数                                       

                    });

            }

        }

转载于:https://www.cnblogs.com/gossip/archive/2011/07/05/2098255.html

C# using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public class StatusToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is bool isEnabled) { return isEnabled ? Brushes.Red : Brushes.Green; } return Brushes.Gray; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class MainViewModel : INotifyPropertyChanged { private bool _isAutoTradingEnabled; public bool IsAutoTradingEnabled { get => _isAutoTradingEnabled; set { _isAutoTradingEnabled = value; OnPropertyChanged(); OnPropertyChanged(nameof(ToggleButtonText)); } } public string ToggleButtonText => IsAutoTradingEnabled ? "关闭自动下单" : "开启自动下单"; public ICommand ToggleCommand => new RelayCommand(ToggleStatus); private void ToggleStatus(object obj) { IsAutoTradingEnabled = !IsAutoTradingEnabled; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class RelayCommand : ICommand { private readonly Action<object> _execute; public RelayCommand(Action<object> execute) => _execute = execute; public bool CanExecute(object parameter) => true; public void Execute(object parameter) => _execute(parameter); public event EventHandler CanExecuteChanged; } } <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="自动下单控制" Height="200" Width="300">> <Window.Resources> <local:StatusToColorConverter x:Key="ColorConverter"/> </Window.Resources> <Window.DataContext> <local:MainViewModel/> </Window.DataContext> <Grid> <Button Content="{Binding ToggleButtonText}" Background="{Binding IsAutoTradingEnabled, Converter={StaticResource ColorConverter}}" Command="{Binding ToggleCommand}" Width="150" Height="40" FontSize="14" FontWeight="Bold" Margin="10"/> </Grid> </Window>
08-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值