如何通过用户控件为自定义依赖属性绑定方法?
现有代码问题梳理
你当前的代码存在几个关键错误,导致无法实现需求:
- 依赖属性
OnClickProperty类型定义为string,但事件处理程序需要的是RoutedEventHandler委托类型,而非方法名字符串 - 属性名
IsNavigator和依赖属性名OnClickProperty不匹配,会导致依赖属性无法正常工作 x:Bind不能直接把字符串形式的方法名绑定到Click事件,事件绑定需要的是委托实例
正确实现方案
我们通过定义接收事件委托的依赖属性,将内部Button的点击事件转发给外部指定的方法:
1. CustomButton.xaml.cs 代码修正
public sealed partial class CustomButton : UserControl { public CustomButton() { this.InitializeComponent(); } // 定义接收外部点击事件处理程序的依赖属性 public static readonly DependencyProperty OnClickProperty = DependencyProperty.Register(nameof(OnClick), typeof(RoutedEventHandler), typeof(CustomButton), new PropertyMetadata(null)); public RoutedEventHandler OnClick { get => (RoutedEventHandler)GetValue(OnClickProperty); set => SetValue(OnClickProperty, value); } // 内部Button的点击事件处理逻辑,转发给外部的OnClick委托 private void InnerButton_Click(object sender, RoutedEventArgs e) { OnClick?.Invoke(this, e); } }
2. CustomButton.xaml 代码调整
无需用x:Bind绑定事件,直接绑定到内部处理方法:
<UserControl x:Class="你的命名空间.CustomButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Button x:Name="InnerButton" Click="InnerButton_Click" Content="自定义按钮" /> </UserControl>
3. Page.xaml 使用方式
保持你原本的写法即可:
<local:CustomButton OnClick="CustomButton1_Click" />
4. Page.xaml.cs 后台代码
继续使用你定义的处理方法:
private void CustomButton1_Click(object sender, RoutedEventArgs e) { // 这里写你的业务逻辑 }
更简洁的替代方案:直接暴露内部Button的Click事件
如果不需要额外处理逻辑,也可以直接把内部Button的Click事件暴露给外部,写法更简单:
public sealed partial class CustomButton : UserControl { public CustomButton() { this.InitializeComponent(); } // 直接暴露内部Button的Click事件 public event RoutedEventHandler Click { add => InnerButton.Click += value; remove => InnerButton.Click -= value; } }
使用时和普通Button一样:
<local:CustomButton Click="CustomButton1_Click" />
内容的提问来源于stack exchange,提问作者Elijah Wasson
相关产品推荐
相关产品推荐

