WPF 自定义控件封装对象的命令属性
无法绑定的属性, 通过附加属性扩展
Xaml页面部分
<e:EventExtension.EventTarget>
<e:EventCommand EventName="PreviewMouseLeftButtonDown"
Command="{Binding PreBtnCommand}"
CommandParameter="123">
</e:EventCommand>
</e:EventExtension.EventTarget>
cs代码部分
public class EventExtension
{
public static EventCommand GetEventTarget(DependencyObject obj)
{
return (EventCommand)obj.GetValue(EventTargetProperty);
}
public static void SetEventTarget(DependencyObject obj, EventCommand value)
{
obj.SetValue(EventTargetProperty, value);
}
public static readonly DependencyProperty EventTargetProperty =
DependencyProperty.RegisterAttached(
"EventTarget", typeof(EventCommand),
typeof(EventExtension),
new PropertyMetadata(null, new PropertyChangedCallback(OnEventTargetChanged)));
private static void OnEventTargetChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// 可以拿到 事件名称 Command
var ec = (e.NewValue as EventCommand);
EventInfo ei = d.GetType().GetEvent(ec.EventName);
// 动态挂载事件
var handler = Delegate.CreateDelegate(
ei.EventHandlerType,
typeof(EventExtension).GetMethod("EventExecute",
BindingFlags.NonPublic | BindingFlags.Static));
ei.AddEventHandler(d, handler);
}
private static void EventExecute(object sender, EventArgs e)
{
// 事件转命令
var ec = GetEventTarget((DependencyObject)sender);
// 如果Command获取为null,有可能是因为EventCommand对象的继承有问题,需要继承Animatable
if (ec.CommandParameter == null)
{
ec.Command?.Execute(e);
}
else
ec.Command?.Execute(ec.CommandParameter);
}
// 尝试:事件方法编写在VM中,然后在页面上进行指定,如何处理?
}
public class EventCommand : Animatable
{
public string EventName { get; set; }
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(EventCommand), new PropertyMetadata(null));
public object CommandParameter
{
get { return (object)GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register("CommandParameter", typeof(object), typeof(EventCommand), new PropertyMetadata(null));
protected override Freezable CreateInstanceCore()
{
return (Freezable)Activator.CreateInstance(GetType());
}
}