English 中文(简体)
为包含按钮的WPF用户控件创建自定义单击事件处理程序?
原标题:
  • 时间:2009-05-20 15:31:31
  •  标签:

您在指定一个点击事件手来控制我们的习俗世界森林论坛用户时,是否发现了一个问题? 我这样做。

当你把这种用户控制放在一个主要窗口时,请说主窗子,MouseLeftButton Down don t work, but the PreviewMouseLeftButton Down像药一样。

但是,想象你们团队中每个开发商在利用用户控制时利用这一活动...... 图书馆的一些用户控制器有MouseLeftButtonDown,其他 PreviewMouseLeftButtonDown...。 你们没有同意吗?

因此,我谈了一个解决办法,但我想有人看一下,是否为创建你称为“Click”的习俗活动手采取了某种合法方法。

在我的用户控制下,我迄今为止已经:

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;

    }

在我的习俗中,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>

现在,在我的主轴心中,我有:

<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=".ImagestnOptions.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>

解释:

在用户控制下,当你点击nes子时,它会执行母体“Click”手工艺。

是否有实现同样效果的有利途径?

最佳回答

不要说什么是 m。 为什么当你能够更方便地建立习俗管制(一种扩大现有控制功能的管制,如布顿)时,你会建立用户控制(一种分类为1的控制)? 假定布顿是你像在 Custom邦那样的唯一控制,我高度建议对你(用户总会)的管制。

Example ofuserControl vstomControl here

希望这一帮助!

问题回答

如果你执行ton子,为什么不仅来自纽顿?

但是,你们都需要回答你们的问题。

if (Click != null) Click(this, EventArgs.Empty);

不妨指出:

(((sender as Button).Parent as Grid).Parent as CustomButton).Click(sender, e);

替换

this.Click(sender, e);

?

除此之外,答案取决于您想要的确切行为。如果您希望单击用户控件的单击事件仅在单击内部按钮时触发,则我认为您正在正确处理它。另一方面,如果您希望单击事件在用户控件边界内的任何位置单击时触发,则最好使用常规按钮控件进行样式处理或继承。请记住,在WPF中,按钮的内容可以是任何其他元素,包括另一个按钮。





相关问题
热门标签