Wpf Datagrid: основные функции, примеры использования и советы
WPF (Windows Presentation Foundation) DataGrid is a powerful control designed for displaying and editing data in a structured format, both row-wise and column-wise. It provides flexible and easy-to-use functionality for data visualization in .NET applications.
DataGrid offers extensive customization options for appearance and behavior. It can display various types of data, including text, numbers, dates, images, etc. DataGrid also allows sorting, filtering, and grouping of data, as well as editing and adding new records.
Here are a few code examples demonstrating the main capabilities of working with DataGrid in WPF:
1. Simple example of creating a DataGrid in XAML:
```xaml
```
2. Example of populating DataGrid with data in code:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsActive { get; set; }
}
public partial class MainWindow : Window
{
public List People { get; set; }
public MainWindow()
{
InitializeComponent();
People = new List()
{
new Person() { Name = "John", Age = 25, IsActive = true },
new Person() { Name = "Mary", Age = 30, IsActive = false },
new Person() { Name = "Alex", Age = 40, IsActive = true }
};
DataContext = this;
}
}
```
3. Example of adding a new record to DataGrid:
```csharp
private void AddButton_Click(object sender, RoutedEventArgs e)
{
People.Add(new Person() { Name = "New User", Age = 0, IsActive = false });
}
```
4. Example of deleting a selected record from DataGrid:
```csharp
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
var selectedPerson = dataGrid.SelectedItem as Person;
if (selectedPerson != null)
{
People.Remove(selectedPerson);
}
}
```
WPF DataGrid also supports styling and templates, allowing you to create customized controls and apply various visual effects. You can also customize data validation and data binding using different approaches, such as MVVM (Model-View-ViewModel).
DataGrid is a highly useful control in WPF, providing numerous capabilities for working with data. It is one of the primary tools for representing and editing tabular data in .NET applications.