wpf 如何在自定义用户控件上创建单击事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19929148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:02:42  来源:igfitidea点击:

How can I create a click event on a custom user control?

c#wpfeventsuser-controls

提问by DaveDev

I've created a custom user control. Is it possible for me to add a click event so that when someone clicks anywhere in the area of the control, a click event is fired?

我创建了一个自定义用户控件。我是否可以添加单击事件,以便当有人单击控件区域中的任何位置时,会触发单击事件?

The user control is defined as:

用户控件定义为:

XAML:

XAML:

<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
    <StackPanel Orientation="Vertical">
        <Image  Source="{Binding TabItemImage}" HorizontalAlignment="Center" Stretch="None" VerticalAlignment="Top" />
        <TextBlock Text="{Binding TabItemText}" FontSize="15" HorizontalAlignment="Center" VerticalAlignment="Bottom" />
    </StackPanel>
</Grid>

C#:

C#:

public partial class TabItem : UserControl
{
    public static readonly DependencyProperty ImageProperty = DependencyProperty.Register("TabItemImage", typeof(string), typeof(TabItem), null);
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("TabItemText", typeof(string), typeof(TabItem), null);

    public string TabItemImage
    {
        get { return (string)GetValue(ImageProperty); }
        set { SetValue(ImageProperty, value); }
    }

    public string TabItemText
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public TabItem()
    {
        InitializeComponent();
        this.DataContext = this;
    }
}

With the usage simply:

用法简单:

<tabs:TabItem TabItemText="OVERVIEW" TabItemImage="/Resources/Images/overview.png" />

Ideally I'd be able to modify the user control so that I could specify the click event, e.g.

理想情况下,我能够修改用户控件,以便我可以指定点击事件,例如

<tabs:TabItem 
    TabItemText="OVERVIEW" 
    TabItemImage="/Resources/Images/options_64.png" 
    Click="TabItem_Clicked"/> <!-- when someone clicks the control, this fires -->

Is this possible? If so, what do I need to do to create a click event on a custom user control?

这可能吗?如果是这样,我需要做什么才能在自定义用户控件上创建单击事件?

采纳答案by Trae Moore

sthotakura, Has a good point and that would be a great way to do it. However, If you don't have more than one click event for this UserControl, Why dont you just use the any of the number of mouseclick events that come with defining a custom UserControl.

sthotakura,有一个很好的观点,这将是一个很好的方法。但是,如果此 UserControl 没有多个单击事件,为什么不使用定义自定义 UserControl 附带的任意数量的鼠标单击事件。

I didn't know you could set the datacontext to its self... That is interesting. I am going modify a custom Dialog that i created now.. :) Thanks for teaching me something.

我不知道你可以将数据上下文设置为它自己......这很有趣。我要修改我现在创建的自定义对话框.. :) 谢谢你教我一些东西。



XAML:

XAML:

<UserControl x:Class="StackTest.TestControl"
             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" 
             mc:Ignorable="d" 
             MouseLeftButtonUp="TestControl_OnMouseLeftButtonUp"
             MouseDoubleClick="TestControl_OnMouseDoubleClick"
             MouseLeftButtonDown="TestControl_OnMouseLeftButtonDown">

  <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
    <StackPanel Orientation="Vertical">
      <Image  Source="{Binding TabItemImage}" HorizontalAlignment="Center" Stretch="None" VerticalAlignment="Top" />
      <TextBlock Text="{Binding TabItemText}" FontSize="15" HorizontalAlignment="Center" VerticalAlignment="Bottom" />
    </StackPanel>
  </Grid>

</UserControl>

CS:

CS:

public partial class TestControl : UserControl
{
    public static readonly DependencyProperty ImageProperty = DependencyProperty.Register("TabItemImage" , typeof(string) , typeof(TabItem) , null);
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("TabItemText" , typeof(string) , typeof(TabItem) , null);

    public string TabItemImage
    {
        get { return (string)GetValue(ImageProperty); }
        set { SetValue(ImageProperty , value); }
    }

    public string TabItemText
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty , value); }
    }

    public TestControl()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    // or

    private void TestControl_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        // Add logic...
    }

    // or

    private void TestControl_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        // Add logic...
    }

    // or

    private void TestControl_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        // Add logic...
    }
}

回答by sthotakura

You need to add custom RoutedEventto your TabItem UserControl, Below is code to add a Custom RoutedEvent:

您需要向RoutedEventTabItem UserControl添加自定义,以下是添加自定义 RoutedEvent 的代码:

public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent(
"Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TabItem));

public event RoutedEventHandler Click
{
    add { AddHandler(ClickEvent, value); }
    remove { RemoveHandler(ClickEvent, value); }
}

void RaiseClickEvent()
{
    RoutedEventArgs newEventArgs = new RoutedEventArgs(TabItem.ClickEvent);
    RaiseEvent(newEventArgs);
}

void OnClick()
{
    RaiseClickEvent();
}

And then in your UserControl InitializeMethod wire up PreviewMouseLeftButtonUp event to fire your Custom RoutedEvent:

然后在您的 UserControl InitializeMethod 中连接 PreviewMouseLeftButtonUp 事件以触发您的自定义 RoutedEvent:

PreviewMouseLeftButtonUp += (sender, args) => OnClick();

There is a pretty good How-toon MSDN discussing this, you might want to read that.

MSDN 上有一个很好的How-to讨论这个,你可能想阅读。

回答by luka

So, I can aswer at the great Post of Sthotakura.

所以,我可以在 Sthotakura 的伟大岗位上回答。

this is your post with the all namespace needs

这是您的帖子,其中包含所有命名空间需求

 using System;
    using System.Windows;
    using System.Windows.Controls;

    namespace YourNameSpace
    {
        partial class OPButton
        {
            /// <summary>
            /// Create a custom routed event by first registering a RoutedEventID
            /// This event uses the bubbling routing strategy
            /// see the web page https://msdn.microsoft.com/EN-US/library/vstudio/ms598898(v=vs.90).aspx 
            /// </summary>
            public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(OPButton));
            /// <summary>
            /// Provide CLR accessors for the event Click OPButton 
            /// Adds a routed event handler for a specified routed event Click, adding the handler to the handler collection on the current element.
            /// </summary>
            public event RoutedEventHandler Click
            {
                add {AddHandler(ClickEvent, value); }
                remove { RemoveHandler(ClickEvent, value); }
            }
            /// <summary>
            /// This method raises the Click event 
            /// </summary>
            private void RaiseClickEvent()
            {
                RoutedEventArgs newEventArgs = new RoutedEventArgs(OPButton.ClickEvent);
                RaiseEvent(newEventArgs);
            }
            /// <summary>
            /// For isPressed purposes we raise the event when the OPButton is clicked
            /// </summary>
            private void OnClick()
            {
                RaiseClickEvent();
            }
        }
    }

Add the following References:

添加以下参考:

Windows;
PresentationCore;
WindowsBase;