生活随笔
收集整理的這篇文章主要介紹了
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中显示行号的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。