经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Windows » 查看文章
c# WPF中System.Windows.Interactivity的使用
来源:jb51  时间:2021/3/1 17:18:29  对本文有异议

背景

   在我们进行WPF开发应用程序的时候不可避免的要使用到事件,很多时候没有严格按照MVVM模式进行开发的时候习惯直接在xaml中定义事件,然后再在对应的.cs文件中直接写事件的处理过程,这种处理方式写起来非常简单而且不用过多地处理考虑代码之间是否符合规范,但是我们在写代码的时候如果完全按照WPF规范的MVVM模式进行开发的时候就应该将相应的事件处理写在ViewModel层,这样整个代码才更加符合规范而且层次也更加清楚,更加符合MVVM规范。

常规用法

1 引入命名空间

  通过在代码中引入System.Windows.Interactivity.dll,引入了这个dll后我们就能够使用这个里面的方法来将事件映射到ViewModel层了,我们来看看具体的使用步骤,第一步就是引入命名控件

  1. xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

  另外还可以通过另外一种方式来引入命名空间,其实这两者间都是对等的。

  1. xmlns:i=http://schemas.microsoft.com/expression/2010/interactivity

2 添加事件对应的Command

  这里以TextBox的GetFocus和LostFocus为例来进行说明

  1. <TextBox Text="CommandBinding">
  2.     <i:Interaction.Triggers>
  3.         <i:EventTrigger EventName="LostFocus">
  4.             <i:InvokeCommandAction Command="{Binding OnTextLostFocus}"
  5.                                    CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type TextBox}}}"/>
  6.         </i:EventTrigger>
  7.         <i:EventTrigger EventName="GotFocus">
  8.             <i:InvokeCommandAction Command="{Binding OnTextGotFocus}"
  9.                                    CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type TextBox}}}"/>
  10.         </i:EventTrigger>
  11.     </i:Interaction.Triggers>
  12. </TextBox>

  这个里面我们重点来看看这个InvokeCommandAction的代码结构

  1. namespace System.Windows.Interactivity
  2. {
  3.     public sealed class InvokeCommandAction : TriggerAction<DependencyObject>
  4.     {
  5.         public static readonly DependencyProperty CommandProperty;
  6.         public static readonly DependencyProperty CommandParameterProperty;
  7.  
  8.         public InvokeCommandAction();
  9.  
  10.         public string CommandName { get; set; }
  11.         public ICommand Command { get; set; }
  12.         public object CommandParameter { get; set; }
  13.  
  14.         protected override void Invoke(object parameter);
  15.     }
  16. }

  这里我们发现这里我们如果我们定义一个Command的话我们只能够在Command中获取到我们绑定的CommandParameter这个参数,但是有时候我们需要获取到触发这个事件的RoutedEventArgs的时候,通过这种方式就很难获取到了,这个时候我们就需要自己去扩展一个InvokeCommandAction了,这个时候我们应该怎么做呢?整个过程分成三步:

2.1 定义自己的CommandParameter

  1. public class ExCommandParameter
  2. {
  3.     /// <summary> 
  4.     /// 事件触发源 
  5.     /// </summary> 
  6.     public DependencyObject Sender { get; set; }
  7.     /// <summary> 
  8.     /// 事件参数 
  9.     /// </summary> 
  10.     public EventArgs EventArgs { get; set; }
  11.     /// <summary> 
  12.     /// 额外参数 
  13.     /// </summary> 
  14.     public object Parameter { get; set; }
  15. }

  这个对象除了封装我们常规的参数外还封装了我们需要的EventArgs属性,有了这个我们就能将当前的事件的EventArgs传递进来了。

2.2 重写自己的InvokeCommandAction

  1. public class ExInvokeCommandAction : TriggerAction<DependencyObject>
  2.     {
  3.  
  4.         private string commandName;
  5.         public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(ExInvokeCommandAction), null);
  6.         public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(ExInvokeCommandAction), null);
  7.         /// <summary> 
  8.         /// 获得或设置此操作应调用的命令的名称。 
  9.         /// </summary> 
  10.         /// <value>此操作应调用的命令的名称。</value> 
  11.         /// <remarks>如果设置了此属性和 Command 属性,则此属性将被后者所取代。</remarks> 
  12.         public string CommandName
  13.         {
  14.             get
  15.             {
  16.                 base.ReadPreamble();
  17.                 return this.commandName;
  18.             }
  19.             set
  20.             {
  21.                 if (this.CommandName != value)
  22.                 {
  23.                     base.WritePreamble();
  24.                     this.commandName = value;
  25.                     base.WritePostscript();
  26.                 }
  27.             }
  28.         }
  29.         /// <summary> 
  30.         /// 获取或设置此操作应调用的命令。这是依赖属性。 
  31.         /// </summary> 
  32.         /// <value>要执行的命令。</value> 
  33.         /// <remarks>如果设置了此属性和 CommandName 属性,则此属性将优先于后者。</remarks> 
  34.         public ICommand Command
  35.         {
  36.             get
  37.             {
  38.                 return (ICommand)base.GetValue(ExInvokeCommandAction.CommandProperty);
  39.             }
  40.             set
  41.             {
  42.                 base.SetValue(ExInvokeCommandAction.CommandProperty, value);
  43.             }
  44.         }
  45.         /// <summary> 
  46.         /// 获得或设置命令参数。这是依赖属性。 
  47.         /// </summary> 
  48.         /// <value>命令参数。</value> 
  49.         /// <remarks>这是传递给 ICommand.CanExecute 和 ICommand.Execute 的值。</remarks> 
  50.         public object CommandParameter
  51.         {
  52.             get
  53.             {
  54.                 return base.GetValue(ExInvokeCommandAction.CommandParameterProperty);
  55.             }
  56.             set
  57.             {
  58.                 base.SetValue(ExInvokeCommandAction.CommandParameterProperty, value);
  59.             }
  60.         }
  61.         /// <summary> 
  62.         /// 调用操作。 
  63.         /// </summary> 
  64.         /// <param name="parameter">操作的参数。如果操作不需要参数,则可以将参数设置为空引用。</param> 
  65.         protected override void Invoke(object parameter)
  66.         {
  67.             if (base.AssociatedObject != null)
  68.             {
  69.                 ICommand command = this.ResolveCommand();
  70.                 /*
  71.                  * ★★★★★★★★★★★★★★★★★★★★★★★★
  72.                  * 注意这里添加了事件触发源和事件参数
  73.                  * ★★★★★★★★★★★★★★★★★★★★★★★★
  74.                  */
  75.                 ExCommandParameter exParameter = new ExCommandParameter
  76.                 {
  77.                     Sender = base.AssociatedObject,
  78.                     Parameter = GetValue(CommandParameterProperty),
  79.                     EventArgs = parameter as EventArgs
  80.                 };
  81.                 if (command != null && command.CanExecute(exParameter))
  82.                 {
  83.                     /*
  84.                      * ★★★★★★★★★★★★★★★★★★★★★★★★
  85.                      * 注意将扩展的参数传递到Execute方法中
  86.                      * ★★★★★★★★★★★★★★★★★★★★★★★★
  87.                      */
  88.                     command.Execute(exParameter);
  89.                 }
  90.             }
  91.         }
  92.         private ICommand ResolveCommand()
  93.         {
  94.             ICommand result = null;
  95.             if (this.Command != null)
  96.             {
  97.                 result = this.Command;
  98.             }
  99.             else
  100.             {
  101.                 if (base.AssociatedObject != null)
  102.                 {
  103.                     Type type = base.AssociatedObject.GetType();
  104.                     PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
  105.                     PropertyInfo[] array = properties;
  106.                     for (int i = 0; i < array.Length; i++)
  107.                     {
  108.                         PropertyInfo propertyInfo = array[i];
  109.                         if (typeof(ICommand).IsAssignableFrom(propertyInfo.PropertyType) && string.Equals(propertyInfo.Name, this.CommandName, StringComparison.Ordinal))
  110.                         {
  111.                             result = (ICommand)propertyInfo.GetValue(base.AssociatedObject, null);
  112.                         }
  113.                     }
  114.                 }
  115.             }
  116.             return result;
  117.         }
  118.  
  119.     } 

  这个里面的重点是要重写基类中的Invoke方法,将当前命令通过反射的方式来获取到,然后在执行command.Execute方法的时候将我们自定义的ExCommandParameter传递进去,这样我们就能够在最终绑定的命令中获取到特定的EventArgs对象了。

2.3 在代码中应用自定义InvokeCommandAction

  1.   <ListBox x:Name="lb_selecthistorymembers"                         
  2.            SnapsToDevicePixels="true"
  3.            ItemsSource="{Binding DataContext.SpecificHistoryMembers,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=my:AnnouncementApp},Mode=TwoWay}"
  4.            HorizontalAlignment="Stretch"
  5.            ScrollViewer.HorizontalScrollBarVisibility="Disabled"
  6.            Background="#fff"
  7.            BorderThickness="1">
  8.            <i:Interaction.Triggers>
  9.               <i:EventTrigger EventName="SelectionChanged">
  10.                  <interactive:ExInvokeCommandAction Command="{Binding DataContext.OnSelectHistoryMembersListBoxSelected,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=my:AnnouncementApp},Mode=TwoWay}"
  11.                               CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}}">
  12.                  </interactive:ExInvokeCommandAction>
  13.               </i:EventTrigger>
  14.           </i:Interaction.Triggers>       
  15. </ListBox>

  注意这里需要首先引入自定义的interactive的命名空间,这个在使用的时候需要注意,另外在最终的Command订阅中EventArgs根据不同的事件有不同的表现形式,比如Loaded事件,那么最终获取到的EventArgs就是RoutedEventArgs对象,如果是TableControl的SelectionChanged事件,那么最终获取到的就是SelectionChangedEventArgs对象,这个在使用的时候需要加以区分。

3  使用当前程序集增加Behavior扩展

  System.Windows.Interactivity.dll中一个重要的扩展就是对Behavior的扩展,这个Behavior到底该怎么用呢?我们来看下面的一个例子,我们需要给一个TextBlock和Button增加一个统一的DropShadowEffect,我们先来看看最终的效果,然后再就具体的代码进行分析。

代码分析

  1 增加一个EffectBehavior

  1. public class EffectBehavior : Behavior<FrameworkElement>
  2. {
  3. protected override void OnAttached()
  4. {
  5. base.OnAttached();
  6.  
  7. AssociatedObject.MouseEnter += AssociatedObject_MouseEnter;
  8. AssociatedObject.MouseLeave += AssociatedObject_MouseLeave;
  9. }
  10.  
  11. private void AssociatedObject_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
  12. {
  13. var element = sender as FrameworkElement;
  14. element.Effect = new DropShadowEffect() { Color = Colors.Transparent, ShadowDepth = 2 }; ;
  15. }
  16.  
  17. private void AssociatedObject_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
  18. {
  19. var element = sender as FrameworkElement;
  20. element.Effect = new DropShadowEffect() { Color = Colors.Red, ShadowDepth = 2 };
  21. }
  22.  
  23. protected override void OnDetaching()
  24. {
  25. base.OnDetaching();
  26. AssociatedObject.MouseEnter -= AssociatedObject_MouseEnter;
  27. AssociatedObject.MouseLeave -= AssociatedObject_MouseLeave;
  28.  
  29. }
  30. }

  这里我们继承自System.Windows.Interactivity中的Behavior<T>这个泛型类,这里我们的泛型参数使用FrameworkElement,因为大部分的控件都是继承自这个对象,我们方便为其统一添加效果,在集成这个基类后我们需要重写基类的OnAttached和OnDetaching方法,这个里面AssociatedObject就是我们具体添加Effect的元素,在我们的示例中这个分别是TextBlock和Button对象。

  2 在具体的控件中添加此效果

  1. <Window x:Class="WpfBehavior.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:local="clr-namespace:WpfBehavior"
  7. xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
  8. mc:Ignorable="d"
  9. Title="MainWindow" Height="450" Width="800">
  10. <Grid>
  11. <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
  12. <TextBlock Text="测试文本" Margin="2" Height="30">
  13. <i:Interaction.Behaviors>
  14. <local:EffectBehavior></local:EffectBehavior>
  15. </i:Interaction.Behaviors>
  16. </TextBlock>
  17. <Button Content="测试" Width="80" Height="30" Margin="2">
  18. <i:Interaction.Behaviors>
  19. <local:EffectBehavior></local:EffectBehavior>
  20. </i:Interaction.Behaviors>
  21. </Button>
  22. </StackPanel>
  23. </Grid>
  24. </Window>

以上就是c# WPF中System.Windows.Interactivity的使用的详细内容,更多关于WPF中System.Windows.Interactivity的资料请关注w3xue其它相关文章!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号