美文网首页
WPF datagrid 行号

WPF datagrid 行号

作者: ichengzi | 来源:发表于2015-10-19 16:01 被阅读275次

WPF datagrid Row number

namespace WpfApplication1
{
     public class DataGridBehavior
    {
        #region DisplayRowNumber property

        public static readonly DependencyProperty DisplayRowNumberProperty =
            DependencyProperty.RegisterAttached("DisplayRowNumber", 
                                                typeof(bool), 
                                                typeof(DataGridBehavior),
                                                new FrameworkPropertyMetadata(false, OnDisplayRowNumberChanged));

        private static void OnDisplayRowNumberChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
        {
            DataGrid grid = source as DataGrid;
            if (grid == null)
                return;
            if ((bool)args.NewValue)
            {
                grid.LoadingRow += onGridLoadingRow;
                grid.UnloadingRow += onGridUnloadingRow;
            }
            else
            {
                grid.LoadingRow -= onGridLoadingRow;
                grid.UnloadingRow -= onGridUnloadingRow;
            }
        }

        #region refresh Nums
        private static void refreshDataGridRowNumbers(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)
                    row.Header = row.GetIndex() + 1;
            }
        }
        #endregion

        #region loading
        private static void onGridLoadingRow(object sender, DataGridRowEventArgs e)
        {
            refreshDataGridRowNumbers(sender);
        }
        private static void onGridUnloadingRow(object sender, DataGridRowEventArgs e)
        {
            refreshDataGridRowNumbers(sender);
        }
        #endregion

        [AttachedPropertyBrowsableForType(typeof(DataGrid))]
        ***************************************************
        public static void SetDisplay(DependencyObject element, bool value)
        {
            element.SetValue(DisplayRowNumberProperty, value);
        }
        ***************************************************
        public static bool GetDisplay(DependencyObject element)
        {
            return (bool)element.GetValue(DisplayRowNumberProperty);
        }

        #endregion
    }
}
<DataGrid Name="dg" Grid.Column="2" 
                 local:DataGridBehavior.Display="True"
                 CanUserAddRows="False">
</DataGrid>

Display

  1. DependencyProperty.RegisterAttached("DisplayRowNumber",
  2. local:DataGridBehavior.Display="True"
  3. setDisplay【display

2,3里的display是相互对应的,并且可以和1,2里的不一样,但是一般写成一样,容易识别。

相关文章

网友评论

      本文标题:WPF datagrid 行号

      本文链接:https://www.haomeiwen.com/subject/davzcttx.html