WPF 自定义控件封装对象的命令属性
1.WPF ContextMenu 绑定问题
2.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());
}
}
本文作者:张小跑
本文链接:https://www.cnblogs.com/zhangxiaopao/p/18194126
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步