如何从用户控件中引发自定义路由事件?

How can I raise a custom Routed Event from user control?(如何从用户控件中引发自定义路由事件?)
本文介绍了如何从用户控件中引发自定义路由事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的用户控件中,我有一个按钮,单击该按钮会引发自定义路由事件.我试图提高它,但它不会在 MainWindow.xaml 中被触发.

In my user control I have a button that, when clicked, would raise a custom Routed Event. I've attempted to raise it, but it doesn't get fired in the MainWindow.xaml.

UserControl 中按钮的 Xaml:

Xaml for the button in UserControl:

<Button x:Name="PART_Add" Content="+" Grid.Column="3" Margin="0,0,0,0" Style="{DynamicResource dTranspButton}" Click="btnAdd_Click"/>

用户控件 C# 代码:

UserControl C# code:

//AddClick Event

        public static readonly RoutedEvent AddClickEvent = EventManager.RegisterRoutedEvent("AddClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(dCB_Props));

        public event RoutedEventHandler AddClick
        {
            add { AddHandler(AddClickEvent, value); }
            remove { RemoveHandler(AddClickEvent, value); }
        }

        void RaiseAddClickEvent()
        {            
            RoutedEventArgs newEventArgs = new RoutedEventArgs(dCB_Props.AddClickEvent);
        }

        protected void OnAddClick()
        {
            RaiseAddClickEvent();
        }

//objects events

        private void btnAdd_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            RaiseAddClickEvent();
        }

MainWindow.xaml 中 UserControl 实例的 Xaml 代码:

Xaml Code for the UserControl Instance in MainWindow.xaml:

<local:dCB_Props x:Name="cb1" Margin="41.166,0,36.19,25" VerticalAlignment="Bottom" Height="30" Width="141" AddClick="dCB_Props_AddClick">
    <local:dCB_Props.Items>
        <ComboBoxItem Content="item1"/>
    </local:dCB_Props.Items>
</local:dCB_Props>

应该在 MainWindow.xaml.cs 中触发的 C# 代码:

C# Code that should get fired in MainWindow.xaml.cs:

private void dCB_Props_AddClick(object sender, System.Windows.RoutedEventArgs e)
{
    MessageBox.Show("This Works");
}

推荐答案

你需要调用

RaiseEvent(new RoutedEventArgs(AddClickEvent));

这篇关于如何从用户控件中引发自定义路由事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)