WPF DataGrid automatically generates the serial number, wpfdatagrid
Requirements and results
During the development of the application of WPF technology, most users will encounter the problem of adding serial numbers to the DataGrid. Today, I will share with you a lot of stackoverflow articles to summarize and improve the methods. Let's take a look at them first, demo download link provided at the end of this Article
Design ideas and code
Here, the single-value converter is applied to the DataGrid row level to obtain the row number of the DataGrid and convert it to the corresponding serial number. The idea and implementation are very simple, and the core code is just a few lines.
Binding:
<DataGridTextColumn Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Converter={StaticResource rowToIndexConverter}}" />
Converter:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { DataGridRow row = value as DataGridRow; if (row != null) return row.GetIndex() + 1; else return -1; }
By the way, it is very convenient to bind the DataGrid data source to the application dictionary type. If you are interested, try again :)
<Maid Header = "Name" Binding = "{Binding [Name]}" Width = "60"/> <maid Header = "Age" Binding = "{Binding [Age]} "Width =" 60 "/> <maid Header =" Time "Binding =" {Binding [Time]} "Width =" 60 "/>
Download
Link: https://pan.baidu.com/s/1dE1dZPn
Password: wa1v