我的路由事件在子元素之前点击了根 UI 元素。这是预期的吗?如何让路由事件首先命中子元素?
目标:如果在“自定义文本框”以外的任何地方输入文本,请将文本放入“默认文本框”
结果:Window_PreviewTextInput 在 custom_PreviewTextInput 之前被点击,即使我的光标焦点在“自定义文本框”上
我应该怎么做?
XAML
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" SizeToContent="WidthAndHeight"
PreviewTextInput="Window_PreviewTextInput"
>
<Grid Margin="100,100,100,100">
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="default" Width="100"/>
<TextBox x:Name="defaultTB" Width="300" Height="50"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="custom" Width="100"/>
<TextBox x:Name="custom" PreviewTextInput="custom_PreviewTextInput" Width="300" Height="50"/>
</StackPanel>
</StackPanel>
</Grid>
</Window>
代码背后:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
//goal: if text is typed anywhere except custom textbox, put text in default textbox
private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Keyboard.Focus(defaultTB);
}
//goal: if text is typed in custom TB, put text there, and end the event routing
private void custom_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = true;
}
}
}