你有没有发现一个问题,当你的自定义WPF usercontrol分配一个点击事件处理程序与嵌套按钮控制?我做。为包含按钮的WPF用户控件创建自定义点击事件处理程序?
当你把这样的用户控件放在一个主窗口中,让我们说Main.xaml,MouseLeftButtonDown不起作用,但是PreviewMouseLeftButtonDown就像一个魅力。
但想象一下,告诉团队中的每个开发人员使用您的usercontrol时使用此事件...您库中的某些usercontrols有MouseLeftButtonDown,其他人PreviewMouseLeftButtonDown ....这是一个混乱你不同意吗?
所以我有一个解决方案,但我希望有人看看是否有一些优雅的方式来创建您的自定义事件处理程序称为“点击”。
在我的用户名为CustomButton.xaml.cs,我到目前为止有:
public partial class CustomButton: UserControl
{
public CustomButton()
: base()
{
this.InitializeComponent();
}
public delegate void ClickHandler(object sender, EventArgs e);
public event EventHandler Click;
public void Button_Click(object sender, RoutedEventArgs e) {//execute daddy's button click
(((sender as Button).Parent as Grid).Parent as CustomButton).Click(sender, e);
e.Handled = false;
}
在我CustomButton.xaml
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="YourCompany.UI.Controls.CustomButton" d:DesignHeight="72.5" d:DesignWidth="200">
<UserControl.Resources>
blablabla
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<Button Style="{DynamicResource CustomButton}"
Width="{Binding ElementName=CustomButton, Path=ActualWidth}"
Cursor="Hand" Foreground="#ffffff" FontSize="28" Margin="8,8,0,12"
HorizontalAlignment="Left"
Content="Custom Button" Click="Button_Click" />
</Grid>
现在我Main.xaml中,来电者,我有:
<Window x:Class="YourCompany.MyProject.Main"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MyProject!" Height="600" Width="800"
MinWidth="800" MinHeight="600" WindowState="Maximized" WindowStartupLocation="CenterScreen"
xmlns:bigbola="clr-namespace:YourCompany.UI.Controls;assembly=YourCompany.UI.Controls">
<mycontrols:CustomButton Name="test" MyImage=".\Images\btnOptions.png" Cursor="Hand"
Texto="See options" Click="test_Click"
Margin="168.367,176.702,253.609,0" ToolTip="See all options" Height="76.682"
VerticalAlignment="Top"></mycontrols:CustomButton>
说明:
在usercontrol中,当你点击嵌套按钮时,它执行它的父定制“Click”处理程序。
有没有一种优雅的方式来实现相同的效果?
是的,我正在阅读您的评论,并考虑创建一个以Button为基础控件的自定义控件。 有很多显示UserControl的示例,所以我开始使用Microsoft Expression Blend构建自定义按钮。 我看到我无法控制点击事件。但后来我将学习如何创建一个简单而优雅的自定义按钮。 – 2009-05-20 19:45:17