Use of DataGrid in Avalonia
DataGrid The data table is a very important control in the client UI. DataGrid in Avalonia is a separate package Avalonia.Controls.DataGrid
. To use DataGrid, you need to press this package in Nuget. The following introduces the installation and use of DataGrid
DataGrid package installation
Need to be installed in Nuget
Version selection, consistent with the Avalonia framework version
When installing, you need to pay attention to that Avalonia.Controls.DataGrid
the version of the package must be consistent with the version of the Avalonia framework, otherwise the installation may not be successful.
The Avalonia framework version is the "Avalonia Version" selected for creating the project, generally or 0.10.18
( 11.0.0-preview4
May 22, 2023 22:31:23)
The Avalonia framework version can also be viewed in "Dependencies → Packages"
If you are using the preview version, in the nuget package manager, you need to check "Include pre-release version" on the right side of the search box to see the preview version.
Use of DataGrid
style reference
Reference the DataGrid style file in App.axaml (or reference it on other interfaces used)
The style file must be referenced, otherwise the DataGrid will not be displayed
<!--下面样式文件二选一-->
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml"/>
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Simple.xaml"/>
The effect of Fluent.xaml:
The style effect is relatively complete
The effect of Simple.xaml:
easier
Use DataGrid
The use of DataGrid is the same as WPF by DataGrid.Columns
writing columns
Differences from WPF:
- The binding property is
Items
- And many attributes need to be initialized by assigning their own values
- For example, if you need to drag the column header to adjust the width, you need to add
CanUserResizeColumns="True"
- You need to drag and drop the column header to adjust the order of the columns, and you need to add it yourself
CanUserReorderColumns="True"
- …
- For example, if you need to drag the column header to adjust the width, you need to add
<DataGrid Name="MyDG" >
<DataGrid.Columns>
<DataGridTextColumn
Width="1*"
Binding="{Binding Id}"
Header="序号" />
<DataGridTextColumn
Width="1*"
Binding="{Binding Name}"
Header="姓名" />
<DataGridTextColumn
Width="1*"
Binding="{Binding Description}"
Header="姓名" />
</DataGrid.Columns>
</DataGrid>
c#
//后台绑定
List<User> users = new List<User>();
users.Add(new User() {
Id=1,Name="张一",Description="1111111"});
users.Add(new User() {
Id=2,Name="张二",Description="2222222"});
MyDG.Items = users;