Avalonia 資料列表元件 [Avalonia DataGrid 四欄位 範例]
Avalonia 資料列表元件 [Avalonia DataGrid 四欄位 範例]
資料來源: copilot
https://docs.avaloniaui.net/docs/reference/controls/datagrid/
copilot~xaml
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:YourNamespace" x:Class="YourNamespace.MainWindow" Title="Avalonia DataGrid 範例" Width="600" Height="400"> <DataGrid x:Name="MyDataGrid" AutoGenerateColumns="False" Items="{Binding DataItems}"> <DataGrid.Columns> <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="*"/> <DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="*"/> <DataGridTextColumn Header="Description" Binding="{Binding Description}" Width="*"/> <DataGridTextColumn Header="Date" Binding="{Binding Date}" Width="*"/> </DataGrid.Columns> </DataGrid> </Window>
copilot~code
using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using System; using System.Collections.ObjectModel; namespace YourNamespace { public class MainWindow : Window { public ObservableCollection<DataItem> DataItems { get; set; } public MainWindow() { InitializeComponent(); #if DEBUG this.AttachDevTools(); #endif DataItems = new ObservableCollection<DataItem> { new DataItem { Name = "項目 1", Value = 1, Description = "描述 1", Date = DateTime.Now }, new DataItem { Name = "項目 2", Value = 2, Description = "描述 2", Date = DateTime.Now.AddDays(1) }, new DataItem { Name = "項目 3", Value = 3, Description = "描述 3", Date = DateTime.Now.AddDays(2) } }; DataContext = this; } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } public class DataItem { public string Name { get; set; } public int Value { get; set; } public string Description { get; set; } public DateTime Date { get; set; } } }
============
reference~xaml
<DataGrid Margin="20" ItemsSource="{Binding People}" GridLinesVisibility="All" BorderThickness="1" BorderBrush="Gray"> <DataGrid.Columns> <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/> <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" /> <DataGridCheckBoxColumn Header="Fictitious?" Binding="{Binding IsFictitious}" /> </DataGrid.Columns> </DataGrid>
reference~code
public class Person { public string FirstName { get; set; } public string LastName { get; set; } public bool IsFictitious { get; set; } public Person(string firstName , string lastName, bool isFictitious) { FirstName = firstName; LastName = lastName; IsFictitious = isFictitious; } } using AvaloniaControls.Models; using System.Collections.Generic; using System.Collections.ObjectModel; namespace AvaloniaControls.ViewModels { public class MainWindowViewModel : ViewModelBase { public ObservableCollection<Person> People { get; } public MainWindowViewModel() { var people = new List<Person> { new Person("Neil", "Armstrong", false), new Person("Buzz", "Lightyear", true), new Person("James", "Kirk", true) }; People = new ObservableCollection<Person>(people); } } }