Behavior

Behavior翻译是行为

在WPF中Behavior的使用时必须引用Blend的程序集。

‪C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.5\Libraries\System.Windows.Interactivity.dll

 System.Windows.Interactivity;

或者通过Nuget包管理来获取。

现在来说说如果使用

behavior是行为,而这个行为是针对控件的。

就目前WPF添加行为的方式可以有附加属性 附加事件 依赖属性等方法。

就特性而言behavior和附加属性很相似。

那么使用方式:

  1. 创建一个由Behavior<DependencyObject>所派生的类

  2. 创建依赖属性(不用回调方法)

  3. 根据你想要的效果来重写Behavior的方法

  4. 在xaml中使用

  public class ATCH : Behavior<System.Windows.Controls.TextBox>
    {
        public static readonly DependencyProperty BackRedProperty = DependencyProperty.Register("BackRed", typeof(bool), typeof(ATCH), new PropertyMetadata(false, null));
          
        public bool BackRed
        {
            get { return (bool)GetValue(BackRedProperty); }
            set { SetValue(BackRedProperty,value); }
        }
      
        
        /// <summary>
        /// 当behavior附加成功时
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
           
        }
        /// <summary>
        /// 当behavior分离时
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
        }

        /// <summary>
        /// 当属性变化时
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
                AssociatedObject.Background = new SolidColorBrush(Colors.Red);
            else
                AssociatedObject.Background = new SolidColorBrush(Colors.Gainsboro);
        }
        /// <summary>
        /// 当属性变化
        /// 此方法触发在OnPropertyChanged后
        /// </summary>
        protected override void OnChanged()
        {
            base.OnChanged();
           
        }
    }

而在xaml中则是

<Window x:Class="Beh.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Beh"
        
        xmlns:AT="http://schemas.microsoft.com/expression/2010/interactivity" 
      
        mc:Ignorable="d" 
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox    Margin="211,147,191,124">
            <AT:Interaction.Behaviors>
                <local:ATCH BackRed="False"  />
            </AT:Interaction.Behaviors>
        </TextBox>
    </Grid>
</Window>

猜你喜欢

转载自www.cnblogs.com/T-ARF/p/10464604.html