如何在WPF 4.5 Datagrid中删除一些不需要的列
本文关键字:删除 不需要 Datagrid WPF | 更新日期: 2023-09-27 17:51:11
我用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>