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
- DependencyProperty.RegisterAttached("DisplayRowNumber",
- local:DataGridBehavior.Display="True"
- setDisplay【display】
2,3里的display是相互对应的,并且可以和1,2里的不一样,但是一般写成一样,容易识别。