附加屬性類
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace DTO.SL
{
/// <summary>
/// 附加屬性類
/// </summary>
public class AttachedBehavior
{
public static readonly DependencyProperty BrushProperty = DependencyProperty.RegisterAttached(
"Brush", typeof(Brush), typeof(AttachedBehavior), new PropertyMetadata(null, new PropertyChangedCallback(OnBrushChanged)));
/// <summary>
/// 屬性修改事件
/// </summary>
public static void OnBrushChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
//獲取屬性所在的控件
TextBlock con = obj as TextBlock;
//註冊控件事件
if (con != null)
{
con.MouseEnter += new MouseEventHandler(OnControlEnter);
con.MouseLeave += new MouseEventHandler(OnControlLeave);
}
}
/// <summary>
/// 獲取屬性的值
/// </summary>
/// <param name="boj"></param>
/// <returns></returns>
public static Brush GetBrush(DependencyObject boj)
{
return (Brush)boj.GetValue(BrushProperty);
}
/// <summary>
/// 設置屬性的值
/// </summary>
/// <param name="boj"></param>
/// <param name="value"></param>
public static void SetBrush(DependencyObject boj, Brush value)
{
boj.SetValue(BrushProperty, value);
}
/// <summary>
/// 鼠標進入事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnControlEnter(object sender, MouseEventArgs e)
{
//獲取當前控件
TextBlock con = (TextBlock)e.OriginalSource;
//設置控件顏色爲紅色
con.Foreground = new SolidColorBrush(Colors.Red);
}
/// <summary>
/// 鼠標離開事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnControlLeave(object sender, MouseEventArgs e)
{
//獲取當前控件
TextBlock con = (TextBlock)e.OriginalSource;
//設置控件的顏色爲控件的附加Brush屬性
con.Foreground = GetBrush(con);
}
}
}
Xaml代碼
xmlns:Custom="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:myConvert="clr-namespace:DTO.SL;assembly=DTO.SL"
<TextBlock Width="100" Text="GOLD" myConvert:AttachedBehavior.Brush="Gold"></TextBlock>
<TextBlock Width="100" Text="Violet" myConvert:AttachedBehavior.Brush="Violet"></TextBlock>
<TextBlock Width="100" Text="LemonChiffon" myConvert:AttachedBehavior.Brush="LemonChiffon"></TextBlock>