写一个WPF的自定义控件,在点击控件中的一个按钮时,需要触发一个事件,使用这个自定义控件的客户,可以订阅这个事件,进行处理。
实现的代码段如下:
1.注册一个路由事件
public static readonly RoutedEvent ClearClickEvent = EventManager.RegisterRoutedEvent (
"ClearClick", RoutingStrategy.Bubble, typeof ( RoutedEventHandler ), typeof ( CustomComboBox ) );
2.在控件界面中
<Button Name="ClearButton" Click="ClearButton_Click"
ToolTip="{Binding Path=ClearToolTipText,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}}}">
</Button>
3.触发事件
private void ClearButton_Click ( object sender, RoutedEventArgs e )
{
RoutedEventArgs newEventArgs = new RoutedEventArgs ( ClearClickEvent );
RaiseEvent ( newEventArgs );
}
4.客户如何使用
<local:CustomComboBox ItemsSource="{Binding CategoryItems.Items}" Text="{Binding DisplayCategoryName}" Width="Auto" MinWidth="120"
HorizontalAlignment="Stretch" VerticalAlignment="Top" DisplayMemberPath="DisplayName"
CustomItemContainerStyle="{StaticResource ComboboxTreeViewStyle}">
<presentation:EventCommander.Mappings>
<presentation:CommandEvent Command="{Binding ClearFilterCategory}" Event="ClearClick"/>
<presentation:CommandEvent Command="{Binding UpdateDataGridRowHintCommand}" Event="CustomMouseClick"/>
</presentation:EventCommander.Mappings>
</local:CustomComboBox>