恭喜,你发布的帖子
发布于 2020-02-01 22:18:15
6楼
3.2 自定义一个扩展的TriggerAction类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Input;
using System.Reflection;
namespace WpfApp02
{
public class ExInvokeCommandAction : TriggerAction<DependencyObject>
{
private string commandName;
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(ExInvokeCommandAction), null);
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register("CommandParameter", typeof(object), typeof(ExInvokeCommandAction), null);
public string CommandName
{
get
{
base.ReadPreamble();
return this.commandName;
}
set
{
if (this.CommandName != value)
{
base.WritePreamble();
this.commandName = value;
base.WritePostscript();
}
}
}
public ICommand Command
{
get
{
return (ICommand)base.GetValue(ExInvokeCommandAction.CommandProperty);
}
set
{
base.SetValue(ExInvokeCommandAction.CommandProperty, value);
}
}
public object CommandParameter
{
get
{
return base.GetValue(ExInvokeCommandAction.CommandParameterProperty);
}
set
{
base.SetValue(ExInvokeCommandAction.CommandParameterProperty, value);
}
}
protected override void Invoke(object parameter)
{
if (base.AssociatedObject != null)
{
ICommand command = this.ResolveCommand();
ExCommandParameter exParameter = new ExCommandParameter
{
Sender = base.AssociatedObject,
Parameter = this.GetValue(CommandParameterProperty),
EventArgs = parameter as EventArgs
};
if (command != null && command.CanExecute(exParameter))
{
command.Execute(exParameter);
}
}
}
private ICommand ResolveCommand()
{
ICommand result = null;
if (this.Command != null)
{
result = this.Command;
}
else
{
if (base.AssociatedObject != null)
{
Type type = base.AssociatedObject.GetType();
PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] array = properties;
for (int i = 0; i < array.Length; i++)
{
PropertyInfo propertyInfo = array[i];
if (typeof(ICommand).IsAssignableFrom(propertyInfo.PropertyType)
&& string.Equals(propertyInfo.Name, this.CommandName, StringComparison.Ordinal))
{
result = (ICommand)propertyInfo.GetValue(base.AssociatedObject, null);
}
}
}
}
return result;
}
}
}
请填写推广理由:
分享
只看
楼主