WPF DataGrid 的应用

WPF DataGrid 的硬核应用

简单使用

使用DataGrid就离不开数据绑定,首先我们以最简单的方式实现数据源和DataGrid控件的绑定。

建立数据模型

public class Employee
    {
        /// <summary>
        /// Set 设置成私有方法时,在数据绑定时,绑定的Mode不能设置成TwoWay,只能实现从数据源更新到View。
        /// </summary>
        public Guid Id { get; private set; }

        /// <summary>
        /// 默认构造函数
        /// 在 DataGrid 中如果数据绑定添加新行,会自动调用默认构造函数,来构造一个实例
        /// </summary>
        public Employee()
        {
            Id = Guid.NewGuid();
            Name = "来自默认构造函数的名称";
            Age = 20;
        }
    
    	/// <summary>
        /// 是试用期
        /// </summary>
        public bool IsTryout { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

    }

    /// <summary>
    /// 性别
    /// </summary>
    public enum Sex
    {
        Male,
        Famale
    }

后面应用的数据模型都是以此基础进行改动。

设置UI界面

<UserControl x:Class="Melphily.View.NormalDataGridView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Melphily.View"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <DataGrid x:Name="datagrid1" AutoGenerateColumns="True" />
    </Grid>
</UserControl>

初始化数据源,绑定数据源

/// <summary>
    /// NormalDataGridView.xaml 的交互逻辑
    /// </summary>
    public partial class NormalDataGridView : UserControl
    {

        List<Employee> Employees = new List<Employee>();

        public NormalDataGridView()
        {
            InitializeComponent();


            for (int i = 0; i < 10; i++)
            {
                Employees.Add(new Employee()
                {
                    Name = "Kangkang" + i,
                    Age = 12 + i,
                    IsTryout = i % 3 == 0
                });
            }
			// 数据源
            datagrid1.ItemsSource = Employees;
        }
    }
    

数据呈现

将UI控件添加到窗体的TabControl中,后面的每次应用都是以此作为模板。

<Window x:Class="Melphily.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:Melphily"
        xmlns:view="clr-namespace:Melphily.View"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TabControl>
            <TabItem Header="默认">
                <view:NormalDataGridView/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

好了,通过以上几步就完成了简单的数据绑定,其界面如下图所示。

在这里插入图片描述

测试–数据源的更改

为了测试我们对DataGrid的操作(修改值、添加行等),数据源会发生什么变化。我们在UI界面上添加一个按钮来获取。

  • 修改UI界面
<UserControl x:Class="Melphily.View.NormalDataGridView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Melphily.View"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
         <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <DataGrid x:Name="datagrid1" AutoGenerateColumns="True" />
        <Button Grid.Column="1" Content="Submit" Click="Button_Click"/>
    </Grid>
</UserControl>

  • 在按钮事件中,查看我们的数据源是否改变。
 		private void Button_Click(object sender, RoutedEventArgs e)
        {
            var s = Employees;
        }

总结

我们通过设置**AutoGenerateColumns=“True” **来实现DataGrid的数据绑定,这种使用在对表格没有特殊样式等要求下是非常便捷和方便的。默认情况下DataGrid的列支持数据的类型有String、int…(DataGridTextColumn)、Enum(DataGridComboBoxColumn)、Boolean(DataGridCheckBoxColumn)、Uri(DataGridHyperlinkColumn)。默认情况下,Text文本会帮我们做修改数据的合法性验证(绑定的数据类型)。

同样,这种默认情况下,我们的表列的名称使用属性的名称代替。如果我们要自定义列名,就需要将**AutoGenerateColumns=“False”**并自己填上定义列类型与列名了。

自定义列名

自定义列名只需要修改我们DataGrid控件的列信息即可,其它地方不做改动。

设置UI界面

<UserControl x:Class="Melphily.View.DataGridUsageView1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Melphily.View"
             xmlns:system="clr-namespace:System;assembly=mscorlib"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.Resources>
        <!-- 获取枚举值,为ComboBox提供数据源 -->
        <ObjectDataProvider x:Key="SexEnumType" MethodName="GetValues" ObjectType="{x:Type system:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type Type="local:Sex"></x:Type>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </UserControl.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <DataGrid Name="dataGrid1"  AutoGenerateColumns="False">
            <DataGrid.Columns>
               
                <DataGridTextColumn Header="编号" Width="80" Binding="{Binding Id, Mode=OneWay}"/>
                <DataGridTextColumn Header="姓名" Width="80" Binding="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                <DataGridComboBoxColumn Header="性别" SelectedItemBinding="{Binding Sex}" ItemsSource="{Binding Source={StaticResource SexEnumType}}"/>
                <DataGridTextColumn Header="年龄" Width="80" Binding="{Binding Age, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                <DataGridCheckBoxColumn Header="试用期" Width="80" Binding="{Binding IsTryout, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                <DataGridTemplateColumn Header="自定义列模板" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Border>
                                <BulletDecorator>
                                    <BulletDecorator.Bullet>
                                        <Ellipse Width="20" Height="20" Fill="Lime"/>
                                    </BulletDecorator.Bullet>
                                    <Rectangle Width="20" Height="20" Fill="Red"/>
                                </BulletDecorator>
                            </Border>
                               
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <Button Grid.Column="1" Content="Submit" Click="Button_Click"/>
    </Grid>
</UserControl>

初始化数据源,绑定数据源

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace Melphily.View
{
    /// <summary>
    /// DataGridUsageView1.xaml 的交互逻辑
    /// </summary>
    public partial class DataGridUsageView1 : UserControl
    {
        List<Employee> Employees = new List<Employee>();
        public DataGridUsageView1()
        {
            InitializeComponent();


            for (int i = 0; i < 10; i++)
            {
                Employees.Add(new Employee()
                {
                    Name = "AutoGenerateColumns = False " + i,
                    Age = 12 + i,
                    IsTryout = i % 3 == 0
                });
            }

            dataGrid1.ItemsSource = Employees;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var s = Employees;
        }
    }
}

数据呈现

<Window x:Class="Melphily.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:Melphily"
        xmlns:view="clr-namespace:Melphily.View"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TabControl>
            <TabItem Header="默认">
                <view:NormalDataGridView/>
            </TabItem>
            <TabItem Header="自定义列名">
                <view:DataGridUsageView1/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Ok ,自定义列名的功能就完成了。按F5开一下效果吧!

在这里插入图片描述

总结

自定义模板值得注意的是,数据绑定时要了解每种列模板能承载的数据模型。其次,提供了DataGridTemplateColumn。这个模板列控件可以按照我们的界面需求进行自定义界面样式和数据绑定,这是该控件亮点之一。

添加行

在上面的示例中,我们可以通过直接操作DataGrid表格就可以实现对数据源的更改。这是我们没有设置CanUserAddRows,默认情况下CanUserAddRows=True。因此我们可以通过控制该值来实现数据行的添加。此次试验我们传统的方式来实现。熟练数据绑定的可以通过数据绑定来操作该属性值。

设置UI界面

<UserControl x:Class="Melphily.View.OperatDataGridView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Melphily.View"
             xmlns:system="clr-namespace:System;assembly=mscorlib"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.Resources>
        <!-- 获取枚举值,为ComboBox提供数据源 -->
        <ObjectDataProvider x:Key="SexEnumType" MethodName="GetValues" ObjectType="{x:Type system:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type Type="local:Sex"></x:Type>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </UserControl.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <DataGrid Name="dataGrid1" CanUserAddRows="False" AutoGenerateColumns="False">
            <DataGrid.Columns>

                <DataGridTextColumn Header="编号" Width="80" Binding="{Binding Id, Mode=OneWay}"/>
                <DataGridTextColumn Header="姓名" Width="80" Binding="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                <DataGridComboBoxColumn Header="性别" SelectedItemBinding="{Binding Sex}" ItemsSource="{Binding Source={StaticResource SexEnumType}}"/>
                <DataGridTextColumn Header="年龄" Width="80" Binding="{Binding Age, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                <DataGridCheckBoxColumn Header="试用期" Width="80" Binding="{Binding IsTryout, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

                <DataGridTemplateColumn Header="自定义列模板" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Border>
                                <BulletDecorator>
                                    <BulletDecorator.Bullet>
                                        <Ellipse Width="20" Height="20" Fill="Lime"/>
                                    </BulletDecorator.Bullet>
                                    <Rectangle Width="20" Height="20" Fill="Red"/>
                                </BulletDecorator>
                            </Border>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

            </DataGrid.Columns>

        </DataGrid>
        <StackPanel Grid.Column="1" VerticalAlignment="Center">
            <Button Content="Add" Click="AddRowButton_Click"/>
            <Button Content="Submit" Click="SubmitButton_Click"/>
        </StackPanel>
    </Grid>
</UserControl>

后台修改

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace Melphily.View
{
    /// <summary>
    /// OperatDataGridView.xaml 的交互逻辑
    /// </summary>
    public partial class OperatDataGridView : UserControl
    {
        List<Employee> Employees = new List<Employee>();
        public OperatDataGridView()
        {
            InitializeComponent();
            for (int i = 0; i < 10; i++)
            {
                Employees.Add(new Employee()
                {
                    Name = "AutoGenerateColumns = False " + i,
                    Age = 12 + i,
                    IsTryout = i % 3 == 0
                });
            }

            dataGrid1.ItemsSource = Employees;
        }

        private void AddRowButton_Click(object sender, RoutedEventArgs e)
        {
            dataGrid1.CanUserAddRows = true;
        }

        private void SubmitButton_Click(object sender, RoutedEventArgs e)
        {
            dataGrid1.CanUserAddRows = false;
        }
    }
}

数据呈现

<Window x:Class="Melphily.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:Melphily"
        xmlns:view="clr-namespace:Melphily.View"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TabControl>
            <TabItem Header="默认">
                <view:NormalDataGridView/>
            </TabItem>
            <TabItem Header="自定义列名">
                <view:DataGridUsageView1/>
            </TabItem>
            <TabItem Header="添加行">
                <view:OperatDataGridView/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

F5测试

在这里插入图片描述

不会出现下面多余的可编辑行,只有在点击Add之后才会出现,点击Submit之后又会消失。

总结

以上该功能是配合了数据双向绑定才完成了,当用户编辑了新添加的列,数据源会默认更新一条数据。

编辑行

编辑行这里只是简单的说两句。在不使用数据绑定时,用户可以根据DataGridRowEditEnding事件来监听编辑完成,从而实现对数据源的更新。在使用数据绑定的时候,只需要将需要修改的数据绑定方式为双向(Mode=TwoWay),修改格式正确情况下,会自动更新数据源。双向绑定方式:Binding="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"。描述:绑定模式->双向,更新数据源的触发事件->PropertyChanged属性更改。

删除行

思路:找到需要删除的行,然后删除数据源中的该行信息,最后更新到界面。

图片转存中…(img-vMz5gSxz-1579256949465)]

不会出现下面多余的可编辑行,只有在点击Add之后才会出现,点击Submit之后又会消失。

总结

以上该功能是配合了数据双向绑定才完成了,当用户编辑了新添加的列,数据源会默认更新一条数据。

编辑行

编辑行这里只是简单的说两句。在不使用数据绑定时,用户可以根据DataGridRowEditEnding事件来监听编辑完成,从而实现对数据源的更新。在使用数据绑定的时候,只需要将需要修改的数据绑定方式为双向(Mode=TwoWay),修改格式正确情况下,会自动更新数据源。双向绑定方式:Binding="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"。描述:绑定模式->双向,更新数据源的触发事件->PropertyChanged属性更改。

删除行

思路:找到需要删除的行,然后删除数据源中的该行信息,最后更新到界面。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值