我一直想知道在 XAML 中为元素创建新事件处理程序的快捷方式或其他方式是什么,当我输入 Click="" VS 向我显示一个使用通用名称创建新事件处理程序的选项,但当我自己选择它时,那么即使我点击它并选择选项“显示代码”,它也不会显示。
我一直在网上寻找答案
我假设您想为 UI 控制创建一个自定义事件。这是一个示例: 在 WPF 中为 TextBox 控件创建一个名为 PartialTextSelected 的自定义事件,您可以按照以下步骤操作:
定义自定义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!");
}
}
}