问题描述
在学习WPF的同时,我创建了一个简单的窗口并放入一个TextBox输入用户名。我最初在此TextBox中放置一些Text值(如用户名)。一旦MouseLeftButtonDown被触发,我希望这个文本消失。以下是我的xaml和C#代码 -
c $ c>事件,总是以 $ c>冒泡事件,因此更适合处理。 RoutedEvent 使用的实际派生 EventArgs 对象在 Tunneling 和相关的冒泡事件。如果一个事件有一个相关的 Tunneling 事件,你可以确定一个附加的处理程序将被调用,而一些控件设置 Tunneling 处理,所以相关的 Bubbling 事件永远不会被调用。
有关路由事件的详细信息,请参阅链接页面。
While learning WPF (I am new to this), I created a simple Window and put one TextBox for entering username. I put some Text value initially in this TextBox (say Username). I wanted this text to disappear as soon as MouseLeftButtonDown is fired. Below is my xaml and C# code-
<TextBox Name="usernameTextBox" Background="Transparent" PreviewMouseLeftButtonDown="usernameTextBox_PreviewMouseLeftButtonDown" HorizontalAlignment="Left" Height="23" Margin="10,103,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="166" Text="Username" />C# code
private void usernameTextBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (usernameTextBox.Text.ToLower() == "username") usernameTextBox.Text = ""; }This however, didn't work. After some search, I came across this SO question.And PreviewMouseLeftButtonDown event worked as expected.
So my question is, what is the difference between these two events and how would I know when to use one and when to use the other?
Thanks!
解决方案Other Microsoft technologies like Windows Forms have standard CLR events. These are described as:
For WPF, Microsoft have introduced RoutedEvents, with three separate Routing Strategies As always, Microsoft has the best explanations of these different strategies (from the linked page):
In simplest terms though, the Tunneling events, always with names starting with Preview, occur before Bubbling events and so are preferable to handle. The actual derived EventArgs object that a RoutedEvent uses is shared between both the Tunneling and the relating Bubbling events. If an event has a related Tunneling event, you can be certain that an attached handler will be called, whereas some controls set the Tunneling event as Handled, so the relating Bubbling event is never called.
Please see the linked page for the full details about Routed Events.
这篇关于PreviewMouseLeftButtonDown和MouseLeftButtonDown WPF之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!