赞
踩
下面以一个例子说明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>
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(); } } }
3.主窗体后台代码(MainWindow.xaml.cs):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MainViewModel viewModel = new MainViewModel();
viewModel.Query();
this.DataContext = viewModel;
}
}
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(); } } }
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; } }
三、运行效果:
其他示例一:
如果不用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>
样式资源:
<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>
其他实例二:
(显示部分按钮)
<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>
其他实例三:
<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>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。