WPF自定义行为Behavior,实现双击控件复制文本
WPF引用xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"后可以设置很多自定义的行为:
<i:Interaction.Triggers> <i:EventTrigger EventName="ValueChanged"> <i:InvokeCommandAction Command="{Binding ValueChangedCommand}" /> </i:EventTrigger> </i:Interaction.Triggers>
<UserControl.Resources> <ControlTemplate x:Key="trackThumb" TargetType="{x:Type Slider}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <Grid> <Track x:Name="PART_Track"> <Track.Thumb> <Thumb Width="10"> <i:Interaction.Triggers> <i:EventTrigger EventName="DragCompleted"> <i:InvokeCommandAction Command="{Binding ValueChangedCommand}" /> </i:EventTrigger> </i:Interaction.Triggers> </Thumb> </Track.Thumb> </Track> </Grid> </Border> </ControlTemplate> </UserControl.Resources>
当时当我们有一些自定义的需求时,需要自定义行为,例如给每个控件添加一个双击复制文本的行为。
1. 定义行为
public class MouseDoubleClickCopyTextBehavior : Behavior<FrameworkElement> { /// <summary> /// 需要复制的内容 /// </summary> public string CopyText { get { return (string)GetValue(CopyTextProperty); } set { SetValue(CopyTextProperty, value); } } public static readonly DependencyProperty CopyTextProperty = DependencyProperty.Register("CopyText", typeof(string), typeof(MouseDoubleClickCopyTextBehavior), new PropertyMetadata(null)); protected override void OnAttached() { base.OnAttached(); AssociatedObject.PreviewMouseLeftButtonDown += AssociatedObject_PreviewMouseLeftButtonDown; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.PreviewMouseLeftButtonDown -= AssociatedObject_PreviewMouseLeftButtonDown; } void AssociatedObject_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (e.ClickCount >= 2) Clipboard.SetDataObject(CopyText); }
2. 控件绑定行为
<Style TargetType="Label" BasedOn="{StaticResource {x:Type Label}}"> <Setter Property="VerticalAlignment" Value="Center" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Label"> <Border> <ContentPresenter Name="ContentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True" > <!-- 绑定自定义行为 --> <i:Interaction.Behaviors>
<hei:MouseDoubleClickCopyTextBehavior CopyText="{Binding ElementName=ContentPresenter,Path=Content}"/> </i:Interaction.Behaviors> </ContentPresenter> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground"><Setter.Value> <SolidColorBrush Color="{DynamicResource DisabledForegroundColor}" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate></Setter.Value> </Setter> </Style>
时间会记录下一切。