我该如何在自定义用户控件上创建一个点击事件?

11

我创建了一个自定义用户控件。我能否添加一个点击事件,以便当某人在控件区域的任何地方单击时触发点击事件?

用户控件定义如下:

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#:

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;
    }
}

使用方法简单:

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

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

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

这是否有可能?如果可以,我需要做什么来创建自定义用户控件上的点击事件?


1
您可以使用附加事件Button.Click="myHandler"。有关详细信息,请参阅http://msdn.microsoft.com/zh-cn/library/bb514616(v=vs.90).aspx。 - eran otzap
3个回答

9
您需要将自定义的 RoutedEvent 添加到您的 TabItem 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();
}

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

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

在 MSDN 上有一个非常好的教程,涉及到 IT 技术的各个方面,你可能会想要阅读一下这篇文章:How-to


4

这个答案Suresh提供,有一个很好的观点,那将是一个很好的方法。然而,如果您对此UserControl没有多个点击事件,您可以使用定义自定义UserControl时附带的任何数量的mouseclick事件之一。

我不知道你可以将数据上下文设置为自身...这很有趣。


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:

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...
    }
}

0

这个答案Suresh提供,需要以下命名空间声明:

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();
        }
    }
}

还有以下参考资料:

Windows;
PresentationCore;
WindowsBase;

你好,Jasper, 你可以在这个链接中查看, https://dev.windows.com/en-us/design或者你尝试在谷歌或其他搜索引擎中搜索吗? - luka

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接