如何在 C# 中将子控件的事件绑定/包装到自定义控件的事件?

卢卡·林德霍尔姆

我正在构建一个自定义控件(或模板化,如果你介意的话),但我不知道如何将自定义控件内按钮的事件(Click)绑定到自定义控件本身的 Click 事件。

我在互联网上搜索过,但有些解决方案仅适用于 WPF(包括 UWP 平台中不可用的类),有些适用于 Visual Basic,有些则不完全是我的情况等等......

这是迄今为止完美运行的代码,为了最好的清除(请注意,我已经更改了项目和命名空间的名称以隐藏它,而是将“SomeClass”替换为“SomeClass”):

自定义控件IconButton.cs

public sealed class IconButton : Control
{
    public IconButton()
    {
        this.DefaultStyleKey = typeof(IconButton);

    }



    public Boolean IconButtonIsLabelVisible
    {
        get { return (Boolean)GetValue(IconButtonIsLabelVisibleProperty); }
        set { SetValue(IconButtonIsLabelVisibleProperty, value); }
    }
    public static readonly DependencyProperty IconButtonIsLabelVisibleProperty =
        DependencyProperty.Register("IconButtonIsLabelVisible", typeof(Boolean), typeof(IconButton), new PropertyMetadata(true));



    public String IconButtonLabel
    {
        get { return (String)GetValue(IconButtonLabelProperty); }
        set { SetValue(IconButtonLabelProperty, value); }
    }
    public static readonly DependencyProperty IconButtonLabelProperty =
        DependencyProperty.Register("IconButtonLabel", typeof(String), typeof(IconButton), new PropertyMetadata("Content"));



    public Double IconButtonLabelMargin
    {
        get { return (Double)GetValue(IconButtonLabelMarginProperty); }
        set { SetValue(IconButtonLabelMarginProperty, value); }
    }
    public static readonly DependencyProperty IconButtonLabelMarginProperty =
        DependencyProperty.Register("IconButtonLabelMargin", typeof(Double), typeof(IconButton), new PropertyMetadata(10));



    public Style IconButtonStyle
    {
        get { return (Style)GetValue(IconButtonStyleProperty); }
        set { SetValue(IconButtonStyleProperty, value); }
    }
    public static readonly DependencyProperty IconButtonStyleProperty =
        DependencyProperty.Register("IconButtonStyle", typeof(Style), typeof(IconButton), new PropertyMetadata(null));



    public IconElement IconButtonIcon
    {
        get { return (IconElement)GetValue(IconButtonIconProperty); }
        set { SetValue(IconButtonIconProperty, value); }
    }
    public static readonly DependencyProperty IconButtonIconProperty =
        DependencyProperty.Register("IconButtonIcon", typeof(IconElement), typeof(IconButton), new PropertyMetadata(0));

}

通用 xaml 模板文件Generic.xaml

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SomeClass.Controls">

<Style TargetType="local:IconButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:IconButton">
                <Button x:Name="ClickButton" Style="{TemplateBinding IconButtonStyle}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" Command="{TemplateBinding Command}" CommandParameter="{TemplateBinding CommandParameter}">
                    <Grid Margin="{TemplateBinding Padding}">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>

                        <ContentPresenter x:Name="Content"
                                Content="{TemplateBinding IconButtonIcon}"
                                Foreground="{TemplateBinding Foreground}" VerticalAlignment="Center"/>

                        <Grid Grid.Column="1" Width="{TemplateBinding IconButtonLabelMargin}"/>

                        <TextBlock Grid.Column="2" Text="{TemplateBinding IconButtonLabel}" Foreground="{TemplateBinding Foreground}" VerticalAlignment="Center"/>
                    </Grid>
                </Button>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

还有MainPage.xaml,我想在其中使用 IconButton:

<Page
x:Class="SomeClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SomeClass"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:testControls="using:SomeClass.Controls"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Grid>
    <testControls:IconButton x:Name="TestButton" Click"?" IconButtonLabelMargin="5" HorizontalAlignment="Center" Foreground="Aqua" VerticalAlignment="Center" Background="Transparent" >
        <testControls:IconButton.IconButtonIcon>
            <SymbolIcon Symbol="Preview"/>
        </testControls:IconButton.IconButtonIcon>
    </testControls:IconButton>
</Grid>

因此,鉴于此代码,我想以某种方式将 IconButton 的 xaml 模板中 ClickButton 的 Click 事件绑定到 IconButton 控件本身的默认 Click 事件,以便它可以通过简单地在主页中轻松使用指定 Click 事件。

谢谢你的好意和关注。

此致。

彼得·托尔 - MSFT

这样做需要覆盖OnApplyTemplate控件中方法,在控件中找到命名的模板部分,并在包装​​器上引发事件。

在您的自定义控件中:

ButtonBase clickButtonPart = null;
public const string ClickButtonTemplatePartName = "ClickButton";
public event EventHandler Click;

protected override void OnApplyTemplate()
{
  // In case the template changes, you want to stop listening to the
  // old button's Click event.
  if (clickButtonPart != null)
  {
    clickButtonPart.Click -= ClickForwarder;
    clickButtonPart = null;
  }

  // Find the template child with the special name. It can be any kind
  // of ButtonBase in this example.
  clickButtonPart = GetTemplateChild(ClickButtonTemplatePartName) as ButtonBase;

  // Add a handler to its Click event that simply forwards it on to our
  // Click event.
  if (clickButtonPart != null)
  {
    clickButtonPart.Click += ClickForwarder;
  }
}

private void ClickForwarder(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
  Click?.Invoke(this, null);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在RxCocoa中将控件事件添加到自定义按钮?

如何在 AvaloniaUI 中将自定义事件从子 UserControl 引发到父控件

如何在C#中创建自定义事件

C#wpf-如何在自定义控件中将文本框错误传递给父级

如何从自定义控件发送“ UIControlEventValueChanged”事件?

如何创建用于自定义控件的事件

如何覆盖自定义Firemonkey控件的click事件

C#Xamarin表单-具有属性的自定义控件上的自定义事件

如何在Mapboxgl中使用事件创建我的自定义控件?

如何在回发时捕获并触发用户控件的自定义事件

如何在Qt C ++中向自定义控件添加属性?

如何在 xaml 中继承用 C# 编写的自定义控件

如何在C#中进行自定义表单控件

如何绑定自定义控件

如何在自定义控件中创建一个按钮以触发onClick事件,并以自定义控件所在的主要形式对其进行处理?

C#如何停止控件的事件

如何在自定义控件中将焦点设置在控件上?

如何在AngularJS中绑定自定义事件?

鼠标事件未在自定义控件C#WPF上触发

如何在我的自定义控件中更改子控件的可见性?

如何在自定义控件中获取控件?

使用Azure B2C登录时如何在自定义页面中嵌入登录控件

我如何在自定义控件中检查特殊枚举的值在C#中已更改

如何处理blackberry10中的自定义控件的触摸事件

如何为动态创建的自定义控件创建点击事件?

如何从自定义控件中的 CollectionView 绑定 ItemsSource?

如何在C#中为动态创建的用户控件创建单击事件?

如何使用自定义元素将子自定义元素包装到div中

如何从自定义用户控件 WPF、C# 中的枚举自定义属性获取值?