我有一个WPF用户控件,包括一个按钮和一个模板。如何将Click事件添加到该按钮?
CloseButton.xaml:
<UserControl x:Class="Toolbox.UserContols.CloseButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Toolbox.UserContols"
mc:Ignorable="d"
d:DesignHeight="10" d:DesignWidth="10">
<UserControl.Resources>
<SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
<ImageBrush x:Key="Button.Static.Background" ImageSource="/Toolbox.Resources;component/Resources/CloseButton.png" Opacity="0.5"/>
<ImageBrush x:Key="Button.MouseOver.Background" ImageSource="/Toolbox.Resources;component/Resources/CloseButton.png" Opacity="1"/>
<Style x:Key="CloseButtonStyle" TargetType="{x:Type Button}">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true" Opacity="0.5">
<ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" Value="{StaticResource Button.MouseOver.Background}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Button Style="{DynamicResource CloseButtonStyle}"/>
</UserControl>
使用CloseButton:
<UserContols:CloseButton x:Name="close" Margin="10" HorizontalAlignment="Right" VerticalAlignment="Top"/>
现在我想像普通按钮一样添加Click事件,但我的UserControl似乎没有onClick选项。
示例代码:
<UserContols:CloseButton x:Name="close" Click="close_onClick" Margin="10" HorizontalAlignment="Right" VerticalAlignment="Top"/>
答案 0 :(得分:1)
这是最简约的解决方案,也许它可以扩展,但现在对此太累了:))
在xaml中命名内部按钮以便能够访问它
<Button Name="innerButton" Style="{DynamicResource CloseButtonStyle}"/>
然后像这样公开事件
public partial class CloseButton : UserControl
{
public event EventHandler Click;
public CloseButton()
{
InitializeComponent();
innerButton.Click += ButtonClick;
}
private void ButtonClick(object sender, RoutedEventArgs e)
{
var eventHandler = this.Click;
if (eventHandler != null)
{
eventHandler(this, e);
}
}
}