Skip to main content
 首页 » 编程设计

c#之如何删除 WPF 4.5 Datagrid 中的几个不需要的列

2024年02月20日19lhb25

我正在使用下面编写的 XAML

<Window x:Class="ERP.WinApp.Views.Admin.Patients" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Title="Patients" Height="auto" MinWidth="1024" Width="1024" ShowInTaskbar="False" Icon="/ERP.WinApp;component/Images/patient.png" WindowStartupLocation="CenterScreen"> 
    <Grid> 
<DataGrid ItemsSource="{Binding}" Grid.Row="1" Name="gridPatients" ></DataGrid> 
</Grid> 
</Window> 

后面的代码写在下面

namespace ERP.WinApp.Views.Admin 
{ 
    /// <summary> 
    /// Interaction logic for Patients.xaml 
    /// </summary> 
    public partial class Patients : Window 
    { 
        public Patients() 
        { 
            InitializeComponent(); 
 
            List<Patient> list = new List<Patient>(); 
            list = // Populate it through some method 
            gridPatients.DataContext = list; 
        } 
 
    } 
} 

Patient 类具有一些简单的属性

public class Patient 
    { 
 
        public int Id { get; set; } 
 
        public string FirstName { get; set; } 
 
        public string MiddleName { get; set; } 
 
        public string LastName { get; set; } 
 
        public string FullName { get{ return this.FirstName+ " " +this.MiddleName+ " " +this.LastName; } } 
 
        public DateTime DOB { get; set; } 
 
        public int Age { get { return DateTime.Today.Year - this.DOB.Year; } } 
 
        public char Gender { get; set; } 
    } 

当我运行该应用程序时,我的数据网格中包含所有包含数据的列,而如果我只想拥有几列,例如跳过 Id 和年龄以及名字、中间名、姓氏,那么最好的方法是什么。

我认为这样做对于我想隐藏的每一列都是不好的方法

gridPatients.Columns[0].Visibility = Visibility.Collapsed; 

请您参考如下方法:

您可以将 AutoGenerateColumns 设置为 false,并添加所需的列。

<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" Grid.Row="1" Name="gridPatients" > 
 <ItemTemplate> 
   <DataTemplate> 
      <DataGridTextColumn Binding={ Path=FirstName}/> 
    ...  
    <DataTemplate> 
 </ItemTemplate> 
</DataGrid>