2025-11-12
C#
00

目录

🔍 问题分析
💡 解决方案
基本的DataGrid使用
自定义样式与模板
💬 互动
📌 分享要点
🔑 结尾

在软件开发的世界里,UI 技术的演进让许多开发者感到迷茫。早年的WinForm虽然简单易用,但随着用户体验要求的提高,这一技术逐渐显露出其不足之处。根据调查,超过70%的开发者表示需要更灵活、更强大的UI解决方案。这正是WPF(Windows Presentation Foundation)应运而生的重要原因。

本文将带您深入了解WPF中至关重要的控件——DataGrid。我们将通过分析从WinForm转型的痛点,提供几种有效的方法,帮助您在WPF中高效使用DataGrid,提升您的开发效率和用户体验。

🔍 问题分析

在WinForm中,开发者常常面对以下几个痛点:

  1. 界面灵活性差:虽然WinForm提供基本的控件,但自定义界面元素的难度较大。
  2. 数据绑定复杂:对于大型数据集,数据绑定的实现技巧有限,且性能不佳。
  3. 样式与主题支持缺乏:难以实现现代化的外观设计。

这些问题使得很多开发者在日常工作中频频遇到挑战。而转向WPF后,利用其强大的数据展示和界面定制能力,可以有效缓解这些痛点。

💡 解决方案

基本的DataGrid使用

在WPF中,DataGrid是一个功能强大的控件,能够高效展示和编辑数据。下面是一个简单的实例,包括加载数据、显示和编辑的功能。

C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppDataGrid { public class Person { public string Name { get; set; } public int Age { get; set; } } }
C#
<Window x:Class="AppDataGrid.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:AppDataGrid" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <DataGrid x:Name="dataGrid" AutoGenerateColumns="False" CanUserAddRows="True" ItemsSource="{Binding}"> <DataGrid.Columns> <DataGridTextColumn Header="姓名" Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/> <DataGridTextColumn Header="年龄" Binding="{Binding Age, UpdateSourceTrigger=PropertyChanged}"/> </DataGrid.Columns> </DataGrid> </Grid> </Window>
C#
using System.Collections.ObjectModel; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace AppDataGrid { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public ObservableCollection<Person> People { get; set; } public MainWindow() { InitializeComponent(); // 初始化数据集 People = new ObservableCollection<Person> { new Person { Name = "张三", Age = 30 }, new Person { Name = "李四", Age = 25 } }; // 设置数据上下文 this.DataContext = People; } } }

image.png

  • 逐行注释
    • AutoGenerateColumns 设置为False可以自定义列。
    • ItemsSource 属性绑定到数据上下文,显示数据。
  • 应用场景:适用于CRUD操作,实现数据的动态响应。
  • 常见坑点:确保DataContext已经设置好,否则数据无法展示,若使用List而非ObservableCollection,UI不会自动更新。

自定义样式与模板

WPF的样式和模板功能让我们能够创建美观的界面。下面是如何更改DataGrid的样式。

C#
using System; using System.Globalization; using System.Windows.Data; namespace AppDataGrid { public class BooleanToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value is bool boolValue && boolValue ? "激活" : "未激活"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value.ToString() == "激活"; } } }
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using System.Windows.Media.Imaging; namespace AppDataGrid { public class BooleanToIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value is bool isActive && isActive ? new BitmapImage(new Uri("pack://application:,,,/Resources/active.png")) // 活跃图标路径 : new BitmapImage(new Uri("pack://application:,,,/Resources/inactive.png")); // 非活跃图标路径 } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
XML
<Window x:Class="AppDataGrid.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:AppDataGrid" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.Resources> <!-- DataGrid 样式 --> <Style TargetType="DataGrid"> <Setter Property="Background" Value="#F9F9F9"/> <Setter Property="BorderBrush" Value="#CCCCCC"/> <Setter Property="RowHeight" Value="30"/> <Setter Property="AlternatingRowBackground" Value="#EAEAEA"/> <Setter Property="SelectionMode" Value="Single"/> <Setter Property="SelectionUnit" Value="FullRow"/> <Setter Property="GridLinesVisibility" Value="None"/> </Style> <Style TargetType="DataGridRow"> <Setter Property="Background" Value="Transparent"/> <Setter Property="Foreground" Value="Black"/> <Setter Property="FontSize" Value="14"/> <Setter Property="BorderBrush" Value="#DDDDDD"/> <Setter Property="BorderThickness" Value="0,0,0,1"/> <Setter Property="Cursor" Value="Hand"/> </Style> <!-- 自定义单元格样式 --> <Style x:Key="DataGridCellStyle" TargetType="DataGridCell"> <Setter Property="BorderBrush" Value="#DDDDDD"/> <Setter Property="BorderThickness" Value="0,0,1,1"/> <Setter Property="Background" Value="Transparent"/> <Setter Property="Foreground" Value="Black"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="DataGridCell"> <Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"> <ContentPresenter /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter TargetName="Border" Property="BorderBrush" Value="#DDDDDD"/> <Setter TargetName="Border" Property="Background" Value="#E0E0E0"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <DataTemplate x:Key="IsActiveCellTemplate"> <StackPanel Orientation="Horizontal"> <Image Source="{Binding IsActive, Converter={StaticResource BooleanToIconConverter}}" Width="20" Height="20"/> <TextBlock Text="{Binding IsActive, Converter={StaticResource BooleanToStringConverter}}" VerticalAlignment="Center" Margin="5,0,0,0"/> </StackPanel> </DataTemplate> </Window.Resources> <Grid> <DataGrid x:Name="dataGrid" AutoGenerateColumns="False" ItemsSource="{Binding}" CellStyle="{StaticResource DataGridCellStyle}"> <DataGrid.Columns> <DataGridTextColumn Header="姓名" Binding="{Binding Name}"/> <DataGridTextColumn Header="年龄" Binding="{Binding Age}"/> <DataGridTemplateColumn Header="激活状态" CellTemplate="{StaticResource IsActiveCellTemplate}"/> </DataGrid.Columns> </DataGrid> </Grid> </Window>

image.png

💬 互动

在您使用WPF进行开发时,您是否也遇到过与数据展示相关的挑战呢?欢迎分享您的经验或问题,让我们一起探讨如何解决!

📌 分享要点

  • “WPF不仅仅是UI的提升,更是数据管理的革命。”
  • “通过数据绑定,应用逻辑与UI得以完美分离。”
  • “样式和模板的使用,让界面设计变得事半功倍。”

🔑 结尾

在本文中,我们深入探讨了从WinForm到WPF的转型之路,尤其是在DataGrid控件的使用上。总结一下:

  1. 数据绑定的强大:WPF的数据绑定机制让数据的管理变得更为简单。
  2. 样式与模板:灵活的样式管理使得应用的外观能跟上时尚的潮流。
  3. 高效的用户体验:使用DataGrid提高了信息展示的效率和用户的交互体验。

觉得有用请转发给更多同行!

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!