How can I raise a custom Routed Event from user control?

南楼画角 提交于 2019-12-21 04:03:23

问题


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.

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"/>

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

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>

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

回答1:


You need to call

RaiseEvent(new RoutedEventArgs(AddClickEvent));


来源:https://stackoverflow.com/questions/10144826/how-can-i-raise-a-custom-routed-event-from-user-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!