WPF DataGrid 在Header中显示行号

Posted dotNET跨平台

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF DataGrid 在Header中显示行号相关的知识,希望对你有一定的参考价值。

在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

如果喜欢,点个赞呗~

以上是关于WPF DataGrid 在Header中显示行号的主要内容,如果未能解决你的问题,请参考以下文章

WPF DataGrid标题Header Binding失效

WPF DataGrid标题Header Binding失效

WPF Grid布局 实现DataGrid控件宽充满布局

WPF中Datagrid控件添加行号

wpf DataGrid加载行号

WPF中datagrid的DataGridTextColumn显示多行