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

时间:2012-04-13 16:37:37

标签: c# wpf user-controls routed-events

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

用于UserControl中按钮的Xaml:

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

UserControl C#代码:

//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代码:

<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#代码:

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

1 个答案:

答案 0 :(得分:19)

您需要致电

RaiseEvent(new RoutedEventArgs(AddClickEvent));