如何在 WPF 中轻松创建具有自定义名称的新事件处理程序?

问题描述 投票:0回答:1

我一直想知道在 XAML 中为元素创建新事件处理程序的快捷方式或其他方式是什么,当我输入 Click="" VS 向我显示一个使用通用名称创建新事件处理程序的选项,但当我自己选择它时,那么即使我点击它并选择选项“显示代码”,它也不会显示。

我一直在网上寻找答案

c# wpf
1个回答
0
投票

我假设您想为 UI 控制创建一个自定义事件。这是一个示例: 在 WPF 中为 TextBox 控件创建一个名为 PartialTextSelected 的自定义事件,您可以按照以下步骤操作:

  1. 创建自定义 TextBox 控件:从 TextBox 派生类。
  2. 添加自定义事件:定义自定义路由事件。
  3. 重写必要的方法:重写 OnSelectionChanged 方法以在选择部分文本时引发自定义事件。

定义自定义TextBox控件:

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

namespace CustomControls
{
    public class PartialTextBox : TextBox
    {
        // Define the routed event
        public static readonly RoutedEvent PartialTextSelectedEvent = EventManager.RegisterRoutedEvent(
            "PartialTextSelected", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(PartialTextBox));

        // Provide CLR accessors for the event
        public event RoutedEventHandler PartialTextSelected
        {
            add { AddHandler(PartialTextSelectedEvent, value); }
            remove { RemoveHandler(PartialTextSelectedEvent, value); }
        }

        // Override OnSelectionChanged to raise the event when partial text is selected
        protected override void OnSelectionChanged(RoutedEventArgs e)
        {
            base.OnSelectionChanged(e);

            if (SelectionLength > 0 && SelectionLength < Text.Length)
            {
                RaiseEvent(new RoutedEventArgs(PartialTextSelectedEvent));
            }
        }
    }
}

在XAML中使用自定义TextBox控件:

<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:CustomControls"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:PartialTextBox Width="200" Height="30" PartialTextSelected="PartialTextBox_PartialTextSelected"/>
    </Grid>
</Window>

在代码隐藏中处理自定义事件:

using System.Windows;

namespace YourNamespace
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void PartialTextBox_PartialTextSelected(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Partial text selected!");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.