当前位置:   article > 正文

WPF DataGrid控件的使用

wpf datagrid

WPF DataGrid控件的使用

下面以一个例子说明DataGrid控件的使用方法:

一、程序框架
使用了MVVM Light框架
在这里插入图片描述
二、主要代码部分(使用MVVM Light框架):
1.主窗体xaml代码 (MainWindow.xaml):

<Window x:Class="WpfApp2.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:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="60"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Grid.Row="0">
            <TextBlock Text="搜索条件:" VerticalAlignment="Center" Margin="10 0 0 0"></TextBlock>
            <TextBox Width="200" Height="25" Margin="10 0 0 0" VerticalContentAlignment="Center" Text="{Binding Search}"></TextBox>
            <Button Content="查找" Width="70" Height="25" Margin="10 0 0 0" Command="{Binding QueryCommand}"></Button>
            <Button Content="重置" Width="70" Height="25" Margin="10 0 0 0" Command="{Binding ResetCommand}"></Button>
            <Button Content="新增" Width="70" Height="25" Margin="10 0 0 0" Command="{Binding AddCommand}"></Button>
        </StackPanel>
        <DataGrid Grid.Row="1" ColumnWidth="*" AutoGenerateColumns="False" CanUserAddRows="False" Margin="10" ItemsSource="{Binding GridModelList}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="序号" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="姓名" Binding="{Binding Name}"/>
                <DataGridTemplateColumn Header="操作">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Button Content="修改" Width="60" Height="25" Background="White" Foreground="Black" CommandParameter="{Binding Id}" Command="{Binding DataContext.EditCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"></Button>
                                <Button Content="删除" Width="60" Height="25" Background="AliceBlue" Foreground="Red" CommandParameter="{Binding Id}" Command="{Binding DataContext.DelCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"></Button>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

2.ViewModel类代码(MainViewModel.cs):

public class MainViewModel : ViewModelBase
    {
        public MainViewModel()
        {
            mylocalDB = new localDB();

            QueryCommand = new RelayCommand(Query);
            ResetCommand = new RelayCommand(()=>
            {
                Search = string.Empty;
                this.Query();
            });

            EditCommand = new RelayCommand<int>(t => Edit(t));
            DelCommand = new RelayCommand<int>(t => Del(t));

            AddCommand = new RelayCommand(Add);
        }
        localDB mylocalDB;

        private string search = string.Empty;
        public string Search
        {
            get { return search; }
            set { search = value;RaisePropertyChanged(); }
        }


        private ObservableCollection<Student> gridModelList;

        public ObservableCollection<Student> GridModelList
        {
            get { return gridModelList; }
            set { gridModelList = value;RaisePropertyChanged(); }
        }

        #region Command
        public RelayCommand QueryCommand { get; set; }
        public RelayCommand ResetCommand { get; set; }

        public RelayCommand<int> EditCommand { get; set; }
        public RelayCommand<int> DelCommand { get; set; }

        public RelayCommand AddCommand { get; set; }
        #endregion
        public void Query()
        {
            var models = mylocalDB.GetStudentsByName(Search);
            GridModelList = new ObservableCollection<Student>();
            if(models != null)
            {
                models.ForEach(arg =>
                {
                    GridModelList.Add(arg);
                });
            }
        }

        public void Edit(int id)
        {
            var model = mylocalDB.GetStudentById(id);
            if(model != null)
            {
                UserView view = new UserView(model);
                var res = view.ShowDialog();
                if(res.Value)
                {
                    var newModel =GridModelList.FirstOrDefault(t=>t.Id == model.Id);
                    if(newModel != null)
                    {
                        newModel.Name = model.Name;
                    }
                }
            }
        }

        public void Add()
        {
            Student stu = new Student();
            UserView view = new UserView(stu);
            var res = view.ShowDialog();
            if (res.Value)
            {
                stu.Id = gridModelList.Max(t => t.Id) + 1; ;
                mylocalDB.AddStudent(stu);
                this.Query();
            }
        }

        public void Del(int id)
        {
            var model = mylocalDB.GetStudentById(id);
            if (model != null)
            {
                var res = MessageBox.Show($"确认删除当前用户:{model.Name}?","操作提示:",MessageBoxButton.OK,MessageBoxImage.Question);
                if(res == MessageBoxResult.OK)
                {
                    mylocalDB.DelStudent(model.Id);
                }
                this.Query();
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103

3.主窗体后台代码(MainWindow.xaml.cs):

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            MainViewModel viewModel = new MainViewModel();
            viewModel.Query();

            this.DataContext = viewModel;
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

4.Student类:

public class Student:ViewModelBase
    {
        private int id;
        private string name;

        public int Id
        {
            get { return id; }
            set 
            {
                id = value;
                RaisePropertyChanged();
            }
        }

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                RaisePropertyChanged();
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

5.localDB类(这里充当数据库功能)

public class localDB
    {
        public localDB()
        {
            Init();
        }
        private List<Student> students;

        private void Init()
        {
            students = new List<Student>();
            for (int i = 0; i < 30; i++)
            {
                students.Add(new Student()
                {
                    Id = i,
                    Name = $"Sample{i}"
                }) ;
            }
        }

        public List<Student> GetStudents()
        {
            return students;
        }

        //新增
        public void AddStudent(Student stu)
        {
            students.Add(stu);
        }

        //删除
        public void DelStudent(int id)
        {
            var model = students.FirstOrDefault(t => t.Id == id);
            if(model!=null)
            {
                students.Remove(model);
            }
        }

        public List<Student> GetStudentsByName(string name)
        {
            return students.Where(q=>q.Name.Contains(name)).ToList();
        }

        public Student GetStudentById(int id)
        {
            var model = students.FirstOrDefault(t=>t.Id == id);
            if(model != null)
            {
                return new Student() { 
                    Id = model.Id,
                    Name = model.Name
                };
            }
            return null;
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60

三、运行效果:
在这里插入图片描述

其他示例一:
如果不用MVVM,DataGrid中的按钮也可以Tag来绑定数据,用事件触发:

 <DataGrid Grid.Row="1" Name="grd" ItemsSource="{Binding FailLists}" Margin="10" HorizontalContentAlignment="Center" AutoGenerateColumns="False" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="False" 
                      CanUserResizeColumns="False" CanUserReorderColumns="False" LoadingRow="Grd_LoadingRow" HeadersVisibility ="Column">
                            <DataGrid.Columns>
                                <DataGridTemplateColumn Header="No." Width="40">
                                    <DataGridTemplateColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridRow}}, Path=Header}" />
                                        </DataTemplate>
                                    </DataGridTemplateColumn.CellTemplate>
                                </DataGridTemplateColumn>
                                <DataGridTextColumn Header="测试项路径" Width="*" Binding="{Binding FailPath}" ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                                <DataGridTemplateColumn Header="操作" Width="120">
                                    <DataGridTemplateColumn.CellTemplate>
                                        <DataTemplate>
                                            <StackPanel Orientation="Horizontal">
                                                <!--<Button Content="Run" Width="40" Height="20" Margin="5 0 10 0" Background="#3CB371" Foreground="White" CommandParameter="{Binding PrjPath}" Command="{Binding DataContext.EditCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"></Button>-->
                                                <Button Name="btn_IDERun" Content="IDE运行" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridRow}}, Path=Header}"  Width="60" Height="20" Margin="2 0 0 0" Style="{StaticResource btnCheck}" Background="#3CB371" Cursor="Hand" Foreground="White" Click="Btn_IDERun_Click"/>
                                                <Button Name="btn_ErrView" Content="LOG" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridRow}}, Path=Header}"  Width="40" Height="20" Margin="3 0 0 0" Style="{StaticResource btnCheck}" Background="#FF9900" Cursor="Hand" Foreground="White" Click="Btn_ErrView_Click"/>
                                            </StackPanel>
                                        </DataTemplate>
                                    </DataGridTemplateColumn.CellTemplate>
                                </DataGridTemplateColumn>
                                <DataGridTextColumn Header="结果" Width="50" Binding="{Binding TestResult}" ElementStyle="{StaticResource DataGridTextColumnCenterSytle_1}"/>
                            </DataGrid.Columns>
                        </DataGrid>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

样式资源:

 <Style x:Key="DataGridTextColumnCenterSytle" TargetType="{x:Type TextBlock}">
            <!--<Setter Property="HorizontalAlignment" Value="Center" />-->
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>

        <Style x:Key="DataGridTextColumnCenterSytle_1" TargetType="{x:Type TextBlock}">
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="FontWeight" Value="Bold"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding TestResult}" Value="Pass">
                    <Setter Property="Foreground"  Value="Green"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding TestResult}" Value="Fail">
                    <Setter Property="Foreground" Value="Red"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

其他实例二:
(显示部分按钮)

<Grid Grid.Row="2" Margin="10 0 10 10">
                        <DataGrid Name="grd" ItemsSource="{Binding JumpLists}" Margin="0,4" Grid.Row="1" FontSize="12"
                      AutoGenerateColumns="False" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="False" 
                      CanUserResizeColumns="False" CanUserReorderColumns="False" HeadersVisibility="Column">
                            <DataGrid.Columns>
                                <!--<DataGridTextColumn Header="系列" Width="100" Binding="{Binding Series}" CanUserResize="False" CanUserSort="False"/>-->
                                <DataGridTextColumn Header="芯片" Width="100" Binding="{Binding ChipName}"  ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                                <DataGridTextColumn Header="封装" Width="100" Binding="{Binding Package}"  ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                                <DataGridTextColumn Header="跳线方式" Width="170" Binding="{Binding JumpMode}"  ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                                <DataGridTextColumn Header="跳线板短接点" Width="*" Binding="{Binding Jmup7Short}"  ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                                <DataGridTemplateColumn Header="短接图" Width="90">
                                    <DataGridTemplateColumn.CellTemplate>
                                        <DataTemplate>
                                            <StackPanel Name="sp_Func" Orientation="Horizontal">
                                                <Button Name="btn_SV03" Content="SV03" Width="35" Height="20" Margin="5 0 5 0" Style="{StaticResource Select_btn}" CommandParameter="{Binding Jmup7Short}" Command="{Binding DataContext.SV03Command,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}" Click="Btn_SV03_Click"></Button>
                                                <Button Name="btn_SV04" Content="SV04" Width="35" Height="20" Style="{StaticResource Select_btn}" CommandParameter="{Binding Jmup7Short}" Command="{Binding DataContext.SV04Command,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}" Click="Btn_SV04_Click"></Button>
                                            </StackPanel>
                                            <DataTemplate.Triggers>
                                                <DataTrigger Binding="{Binding ViewPart}" Value="True">
                                                    <Setter Property="Visibility" Value="Visible"/>
                                                </DataTrigger>
                                                <DataTrigger Binding="{Binding ViewPart}" Value="False">
                                                    <Setter Property="Visibility" Value="Collapsed"/>
                                                </DataTrigger>
                                            </DataTemplate.Triggers>
                                        </DataTemplate>
                                    </DataGridTemplateColumn.CellTemplate>
                                </DataGridTemplateColumn>
                            </DataGrid.Columns>
                        </DataGrid>
                    </Grid>
                </Grid>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

其他实例三:

<DataGrid ItemsSource="{Binding ProductsList}" AutoGenerateColumns="False" CanUserAddRows="False" CanUserSortColumns="False"
                      CanUserResizeColumns="False" CanUserReorderColumns="False" HeadersVisibility="Column" AlternationCount="2" IsReadOnly="True">
                <DataGrid.ColumnHeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="HorizontalContentAlignment" Value="Center"/>
                        <Setter Property="BorderThickness" Value="1"></Setter>
                        <Setter Property="Background" Value="#FFE699"></Setter>
                        <Setter Property="FontSize" Value="16"/>
                        <Setter Property="Height" Value="30"/>
                        <!--设置边框笔刷(BorderBrush)-->
                        <Setter Property="BorderBrush">
                            <!---->
                            <Setter.Value>
                                <!--色刷,Opacity:透明度-->
                                <SolidColorBrush Color="#333" Opacity="0.1"></SolidColorBrush>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </DataGrid.ColumnHeaderStyle>
                <DataGrid.RowStyle>
                    <Style TargetType="{x:Type DataGridRow}">
                        <Style.Triggers>
                            <Trigger Property="ItemsControl.AlternationIndex"
                         Value="0">
                                <Setter Property="Background" Value="#FFFFFFFF" />
                            </Trigger>
                            <Trigger Property="ItemsControl.AlternationIndex"
                         Value="1">
                                <Setter Property="Background" Value="#FFC5E0B3" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </DataGrid.RowStyle>
                <DataGrid.Columns>
                    <DataGridTextColumn Width="120" Header="产品名称" Binding="{Binding Name}" ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                    <DataGridTextColumn Width="90" Header="触控通道" Binding="{Binding Pins}" ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                    <DataGridTextColumn Width="90" Header="输出型态" Binding="{Binding Out}" ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                    <DataGridTextColumn Width="100" Header="封装" Binding="{Binding Package}" ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                    <DataGridTextColumn Width="*" Header="功能描述" Binding="{Binding Describe}" ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                    <DataGridTextColumn Width="100" Header="校验码" Binding="{Binding Checksum}" ElementStyle="{StaticResource DataGridTextColumnCenterSytle}"/>
                    <DataGridTemplateColumn Header="文档下载" Width="80">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Grid>
                                    <Button Name="bt_downPDK" Style="{StaticResource down_btn}" Width="20" Height="20" Cursor="Hand" Tag="{Binding Name}" Click="Bt_downPDK_Click" >
                                        <Button.Background>
                                            <ImageBrush ImageSource="Images/download.png"/>
                                        </Button.Background>
                                    </Button>
                                    <TextBlock Name="tb_line" Text="-" FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                </Grid>
                                <DataTemplate.Triggers>
                                    <DataTrigger Binding="{Binding Download}" Value="true">
                                        <Setter TargetName="bt_downPDK" Property="Visibility" Value="Visible"/>
                                        <Setter TargetName="tb_line" Property="Visibility" Value="Collapsed"/>
                                    </DataTrigger>
                                    <DataTrigger Binding="{Binding Download}" Value="false">
                                        <Setter TargetName="bt_downPDK" Property="Visibility" Value="Collapsed"/>
                                        <Setter TargetName="tb_line" Property="Visibility" Value="Visible"/>
                                    </DataTrigger>
                                </DataTemplate.Triggers>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/582836?site
推荐阅读
相关标签
  

闽ICP备14008679号