在软件开发的世界里,UI 技术的演进让许多开发者感到迷茫。早年的WinForm虽然简单易用,但随着用户体验要求的提高,这一技术逐渐显露出其不足之处。根据调查,超过70%的开发者表示需要更灵活、更强大的UI解决方案。这正是WPF(Windows Presentation Foundation)应运而生的重要原因。
本文将带您深入了解WPF中至关重要的控件——DataGrid。我们将通过分析从WinForm转型的痛点,提供几种有效的方法,帮助您在WPF中高效使用DataGrid,提升您的开发效率和用户体验。
在WinForm中,开发者常常面对以下几个痛点:
这些问题使得很多开发者在日常工作中频频遇到挑战。而转向WPF后,利用其强大的数据展示和界面定制能力,可以有效缓解这些痛点。
在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;
}
}
}

AutoGenerateColumns 设置为False可以自定义列。ItemsSource 属性绑定到数据上下文,显示数据。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>

在您使用WPF进行开发时,您是否也遇到过与数据展示相关的挑战呢?欢迎分享您的经验或问题,让我们一起探讨如何解决!
在本文中,我们深入探讨了从WinForm到WPF的转型之路,尤其是在DataGrid控件的使用上。总结一下:
觉得有用请转发给更多同行!
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!