[英]Is it possible to add more columns to a DataGrid when AutogenerateColumns==True?
Simply put, I have a DataGrid
in my XML file that I bound to a list - in this example, a list of Person
s. 简单地说,我在我的XML文件中有一个
DataGrid
,我绑定到一个列表 - 在本例中,是一个Person
列表。 However, I also want an extra column, as all entries in this list are going to be a subclass of Person
, ie PersonWithAge
. 但是,我还想要一个额外的列,因为此列表中的所有条目都将成为
Person
的子类,即PersonWithAge
。 I am not allowed to change the type of ListOfPeople
, though. 但是我不允许更改
ListOfPeople
的类型。
If I add the column in XAML manually, it crashes right away. 如果我手动在XAML中添加列,它会立即崩溃。 How can I add this columns and synchronise it with all the rest?
如何添加此列并将其与所有其他列同步? Is there some way to cast it within the XAML file?
有没有办法在XAML文件中强制转换它? Or can one be added in the
m_grid_AutoGeneratingColumn
method? 或者可以在
m_grid_AutoGeneratingColumn
方法中添加一个?
This is my code: 这是我的代码:
// In MyGridView.xaml.cs
public class MyGridView
{
public ObservableCollection<Person> ListOfPeople { get; set; }
private void m_grid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
/* Some formatting here... */
}
}
public class Person
{
public string Name { get; set; }
}
public class PersonWithAge : Person
{
public int Age{ get; set; }
}
And the XAML code: 和XAML代码:
// MyGridView.xaml
<UserControl x:Class="Project.MyGridView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<DataGrid Name="m_myGrid"
ItemsSource="{Binding ListOfPeople}
AutoGenerateColumns="True" AutoGeneratingColumn="m_grid_AutoGeneratingColumn" >
<!--DataGridTextColumn Header="Age" /--> <!-- This makes the thing crash -->
</DataGrid >
</Grid>
</UserControl>
Move columns you are adding in DataGrid.Columns
移动要在
DataGrid.Columns
中添加的列
<DataGrid Name="m_myGrid"
ItemsSource="{Binding ListOfPeople}
AutoGenerateColumns="True" AutoGeneratingColumn="m_grid_AutoGeneratingColumn" >
<DataGrid.Columns>
<DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
</DataGrid.Columns>
</DataGrid >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.