我有一个带有搜索栏和搜索按钮的用户控件,我正在窗口中显示它们。单击按钮时,我希望事件冒泡到窗口,我可以在窗口后面的代码中执行操作。我不想将按钮点击代码放在用户控制代码后面。我该怎么做?
窗口的 xaml 如下所示:
<dx:DXWindow
x:Class="Client.Support.AskAQuestionDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
xmlns:libRes="clr-namespace:Shared.Lib.Resources;assembly=Shared.Lib"
xmlns:support="clr-namespace:Client.Support"
xmlns:gui="clr-namespace:Client.GUI;assembly=Client.GUI"
Title="{x:Static libRes:Strings.AskAQuestion}" Loaded="DXWindow_Loaded"
Height="150" Width="700">
<Grid>
<Viewbox>
<support:ZenForumSearchBar VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Viewbox>
</Grid>
</dx:DXWindow>
在 UserControl 的代码后面,我有 Click 事件的代码
private void Button_Click(object sender, RoutedEventArgs e)
{
RaiseEvent(e);
}
在包含用户控件的窗口中,我尝试创建一个处理程序来处理这样的事件
private void ButtonHandler(object sender, RoutedEventArgs e)
{
FrameworkElement fe = e.Source as FrameworkElement;
switch (fe.Name)
{
case "_knowledgeBaseSearchButton":
break;
}
e.Handled = true;
}
我认为我做的一切都完全错误。如何让 UserControl 中发生的事件冒泡到实例化的窗口?
最佳答案
Button.Click
已经是冒泡事件,因此您的 UserControl
中不需要 Button_Click
。您需要做的就是在 Window
、Grid
或 ViewBox
<Grid Button.Click="ButtonHandler">
并在处理程序中检查e.OriginalSource
而不是e.Source
var fe = e.OriginalSource as FrameworkElement;
它应该可以工作
关于c# - 如何将事件从用户控件冒泡到包含该事件的窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23567309/