讓我們從元素樹開始。最上面的元素是一個WPF窗口,它已經註冊了ApplicationCommands.Find
命令。 某些子元素具有KeyBinding,並且手勢鍵ENTER指向此命令。這沒關係,如果有人按下ENTER鍵,命令將被執行。 其中我有一個自定義控件,用於搜索和選擇一些元素的彈出窗口。在這個地方,雖然, 我不想讓自定義控件之外的關鍵事件冒泡。但我設置e.handled = true
爲 KeyDown += new KeyEventHandler (..)
,這應該是冒泡路由事件,該自定義控件內的所有控件(文本框等)都將忽略任何類型的輸入。 但我只是想停止在CustomControl的級別冒泡,說:從葉子到最頂層的控制父級,而不是進一步! 這是爲什麼?我不過濾PreviewKeyDown
,所以事件必須傳播到葉,然後它應該回到父,但它不。WPF防止事件在控件之外冒泡
謝謝
編輯:示例代碼:
<UserControl x:Class="WpfApplication5.TestUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<StackPanel Orientation="Vertical">
<TextBox />
<TextBox />
<TextBox />
</StackPanel>
</UserControl>
/*
* I want to stop bubbling at this level. Let us say if we click 'enter' on the level of the TextBox leaf,
* it should propagate until the TestUserControl is reached and then stop.
*/
public partial class TestUserControl : UserControl
{
public TestUserControl()
{
InitializeComponent();
}
}
<Window x:Class="WpfApplication5.Window6"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication5"
Title="Window6" Height="300" Width="300">
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Find" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Gesture="Enter" Command="ApplicationCommands.Find" />
</Window.InputBindings>
<Grid>
<local:TestUserControl />
</Grid>
</Window>
public partial class Window6 : Window
{
public Window6()
{
InitializeComponent();
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Executed");
}
}
不完全。我想停止傳播事件到自定義控件的主窗口..但是,謝謝 – 2012-04-17 07:07:40
這就是我所理解的。我認爲一些代碼可能會有幫助。 – Natxo 2012-04-17 08:26:41
嗨PaN1C,我編輯我的答案後,您的示例代碼 – Natxo 2012-04-18 08:51:07