Public classGridhelper {//Note: The following three pieces of code can be generated by Propa this shortcut Public Static BOOLgetshowborder (DependencyObject obj) {return(BOOL) obj. GetValue (Showborderproperty); } Public Static voidSetshowborder (DependencyObject obj,BOOLvalue) {obj. SetValue (showborderproperty, value); } Public Static ReadOnlyDependencyProperty Showborderproperty =dependencyproperty.registerattached ("Showborder",typeof(BOOL),typeof(Gridhelper),NewPropertyMetadata (onshowborderchanged)); //This is an event handler that needs to be written manually and must be a static method Private Static voidonshowborderchanged (DependencyObject D, DependencyPropertyChangedEventArgs e) {varGrid = d asGrid; if((BOOL) {e.oldvalue) {grid. Loaded-= (s, arg) = = { }; } if((BOOL) {e.newvalue) {grid. Loaded+ = (s, arg) = = { //The improved approach is not to simply add borders based on rows and columns, but based on the number of top-level child controls in the grid, taking into account the merging situation varControls =grid. Children; varCount =controls. Count; for(inti =0; I < count; i++) { varitem = Controls[i] asFrameworkElement; varborder =NewBorder () {BorderBrush=NewSolidColorBrush (Colors.lightgray), BorderThickness=NewThickness (1) }; varrow =Grid.getrow (item); varColumn =Grid.getcolumn (item); varrowspan =Grid.getrowspan (item); varColumnSpan =Grid.getcolumnspan (item); Grid.setrow (border, Row); Grid.setcolumn (Border, column); Grid.setrowspan (border, rowspan); Grid.setcolumnspan (border, ColumnSpan); Grid. Children.add (border); } }; } } }
Grid Draw Border