在Datagrid中显示行号,如果你绑定的datacontext中没有序号,又想要显示序号的时候,可以按照本文的方法显示喽~
效果如下图:
来看看代码吧~
MainWindow.xaml
<Window x:Class="wpfcore.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:wpfcore" xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"mc:Ignorable="d"Background="#2D2D30"SnapsToDevicePixels="True"FontSize="18"UseLayoutRounding="True"Title="MainWindow" Width="820" Height="340"><Grid><Grid.RowDefinitions><RowDefinition Height="*"/><RowDefinition Height="auto"/></Grid.RowDefinitions><DataGrid x:Name="dg" ItemsSource="{Binding Items}" RowHeaderWidth="50" Grid.Row="0" CanUserAddRows="False"/><StackPanel Grid.Row="1" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center"><Button Padding="18" Content="添加" Click="Add"></Button><Button Padding="18" Content="删除" Click="Remove"></Button></StackPanel></Grid>
</Window>
MainWindow.cs代码:
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;namespace wpfcore
{public partial class MainWindow : Window{public ObservableCollection<Item> Items { get; set; }public MainWindow(){InitializeComponent();DataContext = this;Items = new ObservableCollection<Item>(){new Item{Age=18,Name="WPF UI"},new Item{Age=18,Name="大佬"},new Item{Age=18,Name="牛逼"},new Item{Age=18,Name="wocao666"},};dg.LoadingRow += (s,e)=>e.Row.Header ="行号"+ e.Row.GetIndex();}private void Add(object sender, RoutedEventArgs e){Items.Add(new Item() { Age = 18, Name = "6666" });}private void Remove(object sender, RoutedEventArgs e){Items.RemoveAt(Items.Count - 1);}}public class Item{public int Age { get; set; }public string Name { get; set; }}
}
思路:在LoadingRow事件中设置Header
如果喜欢,点个赞呗~