diff --git a/HandyControl/Controls/Attach/DataGridAttach.cs b/HandyControl/Controls/Attach/DataGridAttach.cs index f122cab3..b3032d7e 100644 --- a/HandyControl/Controls/Attach/DataGridAttach.cs +++ b/HandyControl/Controls/Attach/DataGridAttach.cs @@ -1,6 +1,10 @@ -using System.Linq; +using System; +using System.Collections.Generic; +using System.Linq; using System.Windows; using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Media; namespace HandyControl.Controls { @@ -206,5 +210,73 @@ namespace HandyControl.Controls } } } + + public static DependencyProperty ShowRowNumberProperty = DependencyProperty.RegisterAttached("ShowRowNumber", typeof(bool), typeof(DataGridAttach), new FrameworkPropertyMetadata(false, OnShowRowNumberChanged)); + + public static bool GetShowRowNumber(DependencyObject target) + { + return (bool)target.GetValue(ShowRowNumberProperty); + } + + public static void SetShowRowNumber(DependencyObject target, bool value) + { + target.SetValue(ShowRowNumberProperty, value); + } + + private static void OnShowRowNumberChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) + { + DataGrid dataGrid = target as DataGrid; + if ((bool)e.NewValue == true) + { + EventHandler loadedRowHandler = null; + loadedRowHandler = (object sender, DataGridRowEventArgs ea) => + { + if (GetShowRowNumber(dataGrid) == false) + { + dataGrid.LoadingRow -= loadedRowHandler; + return; + } + ea.Row.Header = ea.Row.GetIndex() + 1; + }; + dataGrid.LoadingRow += loadedRowHandler; + + ItemsChangedEventHandler itemsChangedHandler = null; + itemsChangedHandler = (object sender, ItemsChangedEventArgs ea) => + { + if (GetShowRowNumber(dataGrid) == false) + { + dataGrid.ItemContainerGenerator.ItemsChanged -= itemsChangedHandler; + return; + } + GetVisualChildCollection(dataGrid). + ForEach(d => d.Header = d.GetIndex()); + }; + dataGrid.ItemContainerGenerator.ItemsChanged += itemsChangedHandler; + } + } + + private static List GetVisualChildCollection(object parent) where T : Visual + { + List visualCollection = new List(); + GetVisualChildCollection(parent as DependencyObject, visualCollection); + return visualCollection; + } + + private static void GetVisualChildCollection(DependencyObject parent, List visualCollection) where T : Visual + { + int count = VisualTreeHelper.GetChildrenCount(parent); + for (int i = 0; i < count; i++) + { + DependencyObject child = VisualTreeHelper.GetChild(parent, i); + if (child is T) + { + visualCollection.Add(child as T); + } + if (child != null) + { + GetVisualChildCollection(child, visualCollection); + } + } + } } -} \ No newline at end of file +}