Address: http://eallies.blog.51cto.com/375118/79022
The extension method is a technical highlight in. NET 3.0. It allows us to customize the extension of some object methods. In this way, we can call a function as a call similar to object. ToString.
The following describes how to extend the ListView control.
1. GetItem and IsInRow.
GetItem and IsInRow are two similar methods. The former is used to extract the row selected by the current mouse, and the latter is used to determine whether the current mouse is in the row. Its implementation is based on the VisualTreeHelper. HitTest method.
1 public static bool IsInRow (this ListView control) 2 {3 try 4 {5 bool value = true; 6 7 HitTestResult result = VisualTreeHelper. hitTest (control, Mouse. getPosition (control); 8 object context = (result. visualHit as FrameworkElement ). dataContext; 9 10 if (context is object []) value = false; 11 12 return value; 13} 14 catch 15 {16 throw; 17} 18} 19 20 public static object GetItem (this ListView control) 21 {22 try 23 {24 object item = null; 25 26 HitTestResult result = VisualTreeHelper. hitTest (control, Mouse. getPosition (control); 27 object context = (result. visualHit as FrameworkElement ). dataContext; 28 29 if (context is object []) = false) item = context; 30 31 return item; 32} 33 catch 34 {35 throw; 36} 37}
2. GetControl and GetPresenter.
To find the control in the template column, we first use the recursive loop method (GetPresenter) to find the container that holds the control, and then find the control (GetControl ). Its implementation is based on the VisualTreeHelper. GetChild method and ContentTemplate. FindName method.
1 public static Control GetControl (this ListView control, string name) 2 {3 try 4 {5 object item = control. getItem (); 6 ContentPresenter presenter = control. itemContainerGenerator. containerFromItem (item ). getPresenter (name); 7 8 return (Control) presenter. contentTemplate. findName (name, presenter); 9} 10 catch 11 {12 throw; 13} 14} 1 public static ContentPresenter GetPresenter (this DependencyObj Ect reference, string name) 2 {3 try 4 {5 for (int I = 0; I <VisualTreeHelper. getChildrenCount (reference); I ++) 6 {7 DependencyObject child = VisualTreeHelper. getChild (reference, I); 8 9 if (child! = Null & child is ContentPresenter) 10 {11 ContentPresenter presenter = child as ContentPresenter; 12 13 object element = presenter. ContentTemplate. FindName (name, presenter); 14 15 if (element! = Null) return presenter; 16} 17 else 18 {19 ContentPresenter presenter = child. GetPresenter (name); 20 21 if (presenter! = Null) return presenter; 22} 23} 24 25 return null; 26} 27 catch 28 {29 throw; 30}