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

Brownish Monster picture Brownish Monster · Apr 13, 2012 · Viewed 18.1k times · Source

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

Answer

Louis Kottmann picture Louis Kottmann · Apr 13, 2012

You need to call

RaiseEvent(new RoutedEventArgs(AddClickEvent));