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

时间:2019-06-02 08:46:26

标签: c# xaml events uwp custom-controls

我正在构建自定义控件(如果您愿意的话,可以使用模板化),但是我不知道如何将自定义控件中的按钮事件(单击)绑定到自定义控件的Click事件本身。

我已经在互联网上进行搜索,但是某些解决方案仅适用于WPF(包括UWP平台中不提供的类),某些解决方案仅适用于Visual Basic,其他解决方案不完全符合我的情况,依此类推... >

这里是到目前为止可以正常工作的代码,以实现最佳的清除效果(请注意,我已更改了项目名称和名称空间的名称以使其隐藏,而改为“ 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>

  

因此,鉴于此代码,我想以某种方式绑定ClickButton中的Click事件   将IconButton的xaml模板设置为默认的Click事件   IconButton控件本身,以便可以在主页上通过以下方式轻松使用   只需指定Click事件即可。

感谢您的友善和关注。

最诚挚的问候。

1 个答案:

答案 0 :(得分:1)

要执行此操作,需要覆盖控件中的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);
}