2021-08-20 WPF控件专题 DataGrid控件详解

Posted 微软MVP Eleven

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2021-08-20 WPF控件专题 DataGrid控件详解相关的知识,希望对你有一定的参考价值。

1.DataGrid控件介绍

DataGrid简介 :MultiSelector Selector ItemsControl —条目控件
网格控件:可以自定义网格显示的数据的控件
自定义网格:列的形式,

ListView:类似网格控件:GridView GridViewColumn --CellTemplate—DataTemplate

常用属性
RowHeaderTemplate 行标题模板
CanUserAddRows 是否添加新行
IsReadOnly 是否可以编辑其中的值
VerticalScrollBarVisibility/HorizontalScrollBarVisibility 垂直/水平滚动条的显示
CurrentItem 当前单元格的行绑定的数据项
CanUserDeleteRows 是否可以删除行 Delete 移除当前选择的行
RowStyle / CellStyle 行/单元格 样式
HeadersVisibility 行和列头的可见性
AlternatingRowBackground 交替行上使用的背景画笔 2 1 whIte 2 lightBlue white lightblue
GridLinesVisibility 显示哪些网格线
VerticalGridLinesBrush/HorizontalGridLinesBrush 垂直/水平网格线画笔
RowHeaderWidth 行标题宽度 ColumnHeaderHeight 列标题高度 RowHeight 行高
AutoGenerateColumns 是否自动创建列 false
SelectionUnit/SelectionMode 选择单元(单元格、行或两者)/单选或多选

DataGrid中的列

DataGridTextColumn 文本显示内容,指定的数据类型为String
DataGridCheckBoxColumn 复选框的形式显示内容,指定的数据类型为Boolean
DataGridComboBoxColumn 下拉列表的形式显示内容,指定的数据类型为Enum
DataGridHyperlinkColumn 超链接的形式显示内容,指定的数据类型为Uri
DataGridTemplateColumn 模板列:自定义显示样式,

2.具体案例

<Window x:Class="WpfAppTest.DataGridWindow"
        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:WpfAppTest"
        mc:Ignorable="d"
        Title="DataGridWindow" Height="450" Width="600" Loaded="Window_Loaded">
        <Grid>
              
                <DataGrid HeadersVisibility="All" AutoGenerateColumns="False"  CanUserAddRows="False" IsReadOnly="False" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden"  AlternationCount="3" RowHeaderWidth="20"  GridLinesVisibility="All" SelectionUnit="FullRow" SelectionMode="Extended"  Background="White" Name="dgList"  ItemsSource="{Binding UserList}" >
                        <DataGrid.RowStyle>
                                <Style TargetType="DataGridRow">
                                        <Setter Property="Background" Value="Transparent"/>
                                        <Style.Triggers>
                                                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                                                        <Setter Property="Background" Value="LightGray"/>
                                                </Trigger>
                                                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                                                        <Setter Property="Background" Value="LightBlue"/>
                                                </Trigger>
                                                <Trigger Property="ItemsControl.AlternationIndex" Value="2">
                                                        <Setter Property="Background" Value="Orange"/>
                                                </Trigger>
                                        </Style.Triggers>
                                </Style>
                        </DataGrid.RowStyle>
                        <DataGrid.Columns>
                                <DataGridTextColumn Header="编号" Binding="{Binding UserId}" Width="50"/>
                                <DataGridTextColumn Header="姓名" Binding="{Binding UserName}" Width="80">
                                        <DataGridTextColumn.HeaderTemplate>
                                                <DataTemplate>
                                                        <TextBlock Text="{Binding}" Foreground="Red"/>
                                                </DataTemplate>
                                        </DataGridTextColumn.HeaderTemplate>
                                     
                                </DataGridTextColumn>
                                <DataGridCheckBoxColumn Header="状态" Binding="{Binding UserState}" Width="50"/>
                                <DataGridComboBoxColumn Header="部门"  SelectedValueBinding="{Binding DeptId}"  Width="100" DisplayMemberPath="DeptName" SelectedValuePath="DeptId"  >
                                        <DataGridComboBoxColumn.ElementStyle>
                                                <Style TargetType="ComboBox">
                                                        <Setter Property="ItemsSource" Value="{Binding DataContext.DeptList,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}"/>
                                                </Style>
                                        </DataGridComboBoxColumn.ElementStyle>
                                        <DataGridComboBoxColumn.EditingElementStyle>
                                                <Style TargetType="ComboBox">
                                                        <Setter Property="ItemsSource" Value="{Binding DataContext.DeptList,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}"/>
                                                </Style>
                                        </DataGridComboBoxColumn.EditingElementStyle>
                                </DataGridComboBoxColumn>


                                <DataGridTemplateColumn Header="年龄"  Width="50" >
                                        <DataGridTemplateColumn.CellTemplate>
                                                <DataTemplate>
                                                        <Label Content="{Binding UserAge}" Foreground="Green" Background="LightBlue"/>
                                                </DataTemplate>
                                        </DataGridTemplateColumn.CellTemplate>
                                        <DataGridTemplateColumn.CellEditingTemplate>
                                                <DataTemplate>
                                                        <TextBox Text="{Binding UserAge}"/>
                                                </DataTemplate>
                                        </DataGridTemplateColumn.CellEditingTemplate>
                                </DataGridTemplateColumn>
                        </DataGrid.Columns>
                </DataGrid>

        </Grid>
</Window>

/// <summary>
/// 获取用户信息列表
/// </summary>
/// <returns></returns>
private List<UserInfoNew> GetUserList()
{
        List<UserInfoNew> list = new List<UserInfoNew>();
        string sql = "select UserId,UserName,UserState,UserAge,DeptId from UserInfos where DeptId>0";
        SqlDataReader dr = SqlHelper.ExecuteReader(sql, 1);
        while (dr.Read())
        {
                UserInfoNew user = new UserInfoNew();
                user.UserId = (int)dr["UserId"];
                user.UserName = dr["UserName"].ToString();
                user.UserState = (int)dr["UserState"] == 1 ? true : false;
                user.UserAge = (int)dr["UserAge"];
                user.DeptId = (int)dr["DeptId"];
                list.Add(user);
        }
        dr.Close();
        return list;
}

/// <summary>
/// 获取部门列表
/// </summary>
/// <returns></returns>
private List<DeptInfo> GetDepts()
{
        List<DeptInfo> list = new List<DeptInfo>();
        string sql = "select DeptId,DeptName from DeptInfos";
        SqlDataReader dr = SqlHelper.ExecuteReader(sql, 1);
        while (dr.Read())
        {
                DeptInfo dept = new DeptInfo();
                dept.DeptId = (int)dr["DeptId"];
                dept.DeptName = dr["DeptName"].ToString();
                list.Add(dept);
        }
        dr.Close();
        return list;
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
        //首先,设置comboBox列的数据源   
        //colDept.DisplayMemberPath = "DeptName";
        //colDept.SelectedValuePath = "DeptId";
        //colDept.ItemsSource = GetDepts();
        //如果没有设置列的Name属性
        //DataGridComboBoxColumn deptCol = dgList.Columns[3] as DataGridComboBoxColumn;
        //deptCol.ItemsSource = GetDepts();

        //dgList.ItemsSource = GetUserList();


        //初始化DGVModel
        DGVModel vmodel = new DGVModel();
        vmodel.UserList = GetUserList();
        vmodel.DeptList = GetDepts();

        this.DataContext = vmodel;
}
}

public class UserInfoNew
{
public int UserId { get; set; }
public string UserName { get; set; }
public bool UserState { get; set; }
public int UserAge { get; set; }
public int DeptId { get; set; }
}

public class DeptInfo
{
public int DeptId { get; set; }
public string DeptName { get; set; }
}

/// <summary>
/// Window的数据上下文
/// </summary>
public class DGVModel
{
public List<UserInfoNew> UserList { get; set; }
public List<DeptInfo> DeptList { get; set; }
}

以上是关于2021-08-20 WPF控件专题 DataGrid控件详解的主要内容,如果未能解决你的问题,请参考以下文章

2021-08-13 WPF控件专题 ComboBox 控件详解

2021-08-19 WPF控件专题 TabControl 控件详解

2021-08-09 WPF控件专题 Button控件详解

2021-08-17 WPF控件专题 Groupbox 控件详解

2021-08-10 WPF控件专题 Image控件详解

2021-08-14 WPF控件专题 Calendar 控件详解