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

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));

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

本文标题为:如何从用户控件中引发自定义路由事件?

基础教程推荐