c# - 如何将事件从用户控件冒泡到包含该事件的窗口?

标签 c# wpf xaml routed-events

我有一个带有搜索栏和搜索按钮的用户控件,我正在窗口中显示它们。单击按钮时,我希望事件冒泡到窗口,我可以在窗口后面的代码中执行操作。我不想将按钮点击代码放在用户控制代码后面。我该怎么做?

窗口的 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。您需要做的就是在 WindowGridViewBox

中附加处理程序
<Grid Button.Click="ButtonHandler">

并在处理程序中检查e.OriginalSource而不是e.Source

var fe = e.OriginalSource as FrameworkElement;

它应该可以工作

关于c# - 如何将事件从用户控件冒泡到包含该事件的窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23567309/

相关文章:

c# - 如何枚举 MVC 5 viewbag

c# - IdentityUser 上的 AuditIgnore - Audit.Net

c# - 按索引获取 DataGrid 行

.net - WPF 错误 CS0433

c# - Windows 7 更新,导致 WPF 应用程序中出现 "Item has already been added. Key in dictionary: controlbrush"

c# - SQLite问题“无法打开数据库文件”

c# - Windows Vista 及更高版本的任务栏右键单击应用程序上下文菜单

c# - 如何动态改变 WPF 窗口的大小?

c# - 无效操作异常 : Can only base on a Style with target type that is base type 'TextBlock'

c# - 在 UWP 中添加图像?