1. 程式人生 > WINDOWS開發 >WPF裡藉助附加屬性讓DataGrid顯示行號

WPF裡藉助附加屬性讓DataGrid顯示行號

大部分表格,都有顯示行號的需求。

WPF裡的DataGrid顯示行號,一般如下方式顯示:

技術分享圖片

在後臺程式碼裡寫上相應的事件處理方法:

技術分享圖片

技術分享圖片

執行效果如下:

技術分享圖片

但是,這樣需要對專案裡的所有需要顯示行號的DataGrid都要寫重複的程式碼。

十分不優雅。

下面介紹一種通過附加屬性的方式,把上面的程式碼進行一下封裝。

然後每次應用的時候,只需要簡單的給DataGrid設定一下屬性即可。

技術分享圖片

#region DisplayRowNumber
        public static bool GetDisplayRowNumber(DependencyObject obj)
        {
            return (bool)obj.GetValue(DisplayRowNumberProperty);
        }

        [AttachedPropertyBrowsableForType(typeof(DataGrid))]
        public static void SetDisplayRowNumber(DependencyObject obj,bool value)
        {
            obj.SetValue(DisplayRowNumberProperty,value);
        }

        /// <summary>
        /// 設定是否顯示行號
        /// </summary>
        public static readonly DependencyProperty DisplayRowNumberProperty =
            DependencyProperty.RegisterAttached("DisplayRowNumber",typeof(bool),typeof(DataGridHelper),new PropertyMetadata(false,OnDisplayRowNumberChanged));

        private static void OnDisplayRowNumberChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
        {
            DataGrid grid = d as DataGrid;
            if (grid == null)
            {
                return;
            }

            if ((bool)e.NewValue)
            {
                grid.LoadingRow += OnGridLoadingRow;
                grid.UnloadingRow += OnGridUnloadingRow;
            }
            else
            {
                grid.LoadingRow -= OnGridLoadingRow;
                grid.UnloadingRow -= OnGridUnloadingRow;
            }
        }

        private static void RefreshDataGridRowNumber(object sender)
        {
            DataGrid grid = sender as DataGrid;
            if (grid == null)
            {
                return;
            }

            foreach (var item in grid.Items)
            {
                var row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(item);
                if (row == null)
                {
                    return;
                }
                row.Header = row.GetIndex() + 1;
            }
        }

        private static void OnGridUnloadingRow(object sender,DataGridRowEventArgs e)
        {
            RefreshDataGridRowNumber(sender);
        }

        private static void OnGridLoadingRow(object sender,DataGridRowEventArgs e)
        {
            RefreshDataGridRowNumber(sender);
        }

        #endregion

  

總結,主要運用了WPF中附加屬性的技術。