WPF自定义控件如何在CmdExec依赖属性为True时自动触发按钮命令
实现方案
第一步:修正CustomButtons类逻辑
你原有代码里的CmdExec依赖属性存在默认值类型错误(传了字符串"True"而非bool值),我们需要补充属性变更回调、模板元素获取逻辑,修改后的代码如下:
public class CustomButtons: Control { // 存储模板内LoadButton的引用 private Button _loadButton; public static readonly DependencyProperty CmdExecProperty = DependencyProperty.Register( nameof(CmdExec), typeof(bool), typeof(CustomButtons), new PropertyMetadata(false, OnCmdExecChanged)); // 修正默认值类型,添加属性变更回调 public bool CmdExec { get => (bool)GetValue(CmdExecProperty); set => SetValue(CmdExecProperty, value); } // 重写该方法获取模板里定义的按钮 public override void OnApplyTemplate() { base.OnApplyTemplate(); _loadButton = GetTemplateChild("LoadButton") as Button; // 模板加载完成时如果CmdExec已经为true,直接执行命令 if (CmdExec && _loadButton?.Command != null) { if (_loadButton.Command.CanExecute(_loadButton.CommandParameter)) { _loadButton.Command.Execute(_loadButton.CommandParameter); // 如果需要单次触发,执行完成后可取消注释下面的代码重置状态 // CmdExec = false; } } } // CmdExec属性变更时触发的回调 private static void OnCmdExecChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not CustomButtons control || (bool)e.NewValue != true) return; // 按钮已加载完成则直接执行命令,未加载则等待OnApplyTemplate处理 if (control._loadButton?.Command != null) { if (control._loadButton.Command.CanExecute(control._loadButton.CommandParameter)) { control._loadButton.Command.Execute(control._loadButton.CommandParameter); // 同上,单次触发可打开下面的注释 // control.CmdExec = false; } } } }
第二步:修正Generic.xaml冗余代码
你现有XAML里的LoadButton写完自闭合标签/>后又多了一个</Button>闭合标签,属于冗余代码,删除即可避免编译报错。
修改完成后只要CmdExec赋值为True,就会自动触发按钮绑定的CopyCommand,和手动点击按钮的执行逻辑、参数传递完全一致。
内容的提问来源于stack exchange,提问作者Manav Mehta
相关产品推荐
相关产品推荐

