如何在DataGrid中隐藏自动生成的列? [英] How to hide automatically generated columns in DataGrid?
问题描述
我已自动从SQL Server的DataTable中填充了DataGrid。我希望用户能够添加或删除可见的列。我最初是这样尝试的:
I've automatically populated a DataGrid from a DataTable from a SQL server. I want the user to be able to add or remove which columns are visible. I originally tried this:
public void populateTaskTable(DataTable dt)
{
//add the whole datatable to the datagrid
dg.DataContext = dt.DefaultView;
dg.Columns[0].Visibility = Visibility.Collapsed;
}
对于相应的xaml(我尝试过使用 AutoGenerateColumns = True
For a corresponding xaml (I've tried both with and without the AutoGenerateColumns="True"
<DataGrid Name="dg" ItemsSource="{Binding}" AutoGenerateColumns="True"
<!-- <DataGrid.Columns></DataGrid.Columns> -->
</DataGrid>
这导致了内存冲突中断,所以我做到了
Which resulted in a memory violation break. So then I did
MessageBox.Show(dg.Columns.Count());
以查看是否正在填充列,即使不是,它也会输出 0
,即使我可以看到程序。
to see if Columns was being populated, which it wasn't, it output a 0
even though I could see the columns in the program.
我从上一个stackoverflow问题中发现 自动生成的列不会添加到列索引中。
I found out from this previous stackoverflow question that "automatically generated columns are not added to the Columns index".
Then from this question I tried updating the DataGrid to get Columns populated like so
taskTable.UpdateLayout();
和
taskTable.Items.Refresh();
什么都没做。
是否可以访问自动生成的DataGrid的属性,还是可以将DataGrid的所有列添加到 Columns
组件?
Is there a way to access the properties of an automatically generated DataGrid, or a way to add all of the columns of the DataGrid to the Columns
component?
预先感谢。
推荐答案
连接 AutoGeneratingColumn 事件
dataGrid.AutoGeneratingColumn += dataGrid_AutoGeneratingColumn;
void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
e.Column.Visibility = Visibility.Collapsed;
}
您可能需要有条件地隐藏列,可以使用
You may need to conditionally hide the columns, you can use
private void DataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "YourProperty")
{
e.Column.Visibility = Visibility.Collapsed;
}
}
或者您可以使用 AutoGeneratedColumns 事件。
Or you can use AutoGeneratedColumns event. It will be fired when all the columns has been generated.
dataGrid.AutoGeneratedColumns += DataGrid1_AutoGeneratedColumns;
void DataGrid1_AutoGeneratedColumns(object sender, EventArgs e)
{
int columnsCount = DataGrid1.Columns.Count;
//You can access the columns here.
}
您引用的链接说自动生成的列未添加到我只是注意到自动生成的列确实已添加到集合中。链接到 System.Web.UI文档的答案很糟糕。 .WebControls.DataGrid
这是非常错误的。
The link you referred says that Automatically generated columns are not added to the Columns collection. I just noticed that Auto generated columns are indeed added to the collection. It is poor answer that links to the documentation of System.Web.UI.WebControls.DataGrid
which is very wrong.
这篇关于如何在DataGrid中隐藏自动生成的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!