WPF 精修篇 附加属性

原文: WPF 精修篇 附加属性

 微软把DLL都开源了  今天看了一下 很多WPF实现内容都在里面

https://referencesource.microsoft.com/

说附加属性 附加属性 是全局属性

用来规范全局变量  等等~ 是也可以 给控件 单独增加属性功能

举栗子

给textbox 增加附加属性 并不会增加 到Textbox 类里

功能 按Tab的时候 会全选 textbox2的内容

增加了一个类 并使用 propa 定义了附加属性


  
  
  1. public class TextChange
  2. {
  3. public static bool GetSelectOn(DependencyObject obj)
  4. {
  5. return ( bool)obj.GetValue(SelectOnProperty);
  6. }
  7. public static void SetSelectOn(DependencyObject obj, bool value)
  8. {
  9. obj.SetValue(SelectOnProperty, value);
  10. }
  11. // Using a DependencyProperty as the backing store for SelectOn. This enables animation, styling, binding, etc...
  12. public static readonly DependencyProperty SelectOnProperty =
  13. DependencyProperty.RegisterAttached( "SelectOn", typeof( bool), typeof(TextChange), new PropertyMetadata( false, onNotify));
  14. private static void onNotify(DependencyObject d, DependencyPropertyChangedEventArgs e)
  15. {
  16. object item = d;
  17. if (item is TextBox)
  18. {
  19. (item as TextBox).GotFocus += (s, arges) =>
  20. {
  21. (item as TextBox).SelectAll();
  22. };
  23. }
  24. }
  25. }

在textbox 界面 引用    xmlns:local="clr-namespace:WpfApplication21" 命名空间

  <TextBox HorizontalAlignment="Left" Height="23" Margin="111,133,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"  local:TextChange.SelectOn="True"  />

 
 

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12075445.html