C# WPF Datagrid 绑定和列显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10535110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Datagrid binding and column display
提问by Wild Goat
I have datatable as Item source for DataGrid, this datatable has lots of columns. Is it possible to display few columns instead all of them without creating a new table?
我有数据表作为 DataGrid 的项目源,这个数据表有很多列。是否可以在不创建新表的情况下显示几列而不是所有列?
采纳答案by Avner Shahar-Kashtan
Yes, it is. Just mark AutoGenerateColumns=Falseand manually define your columns. You can use normal text-bound columns, checkbox columns, custom XAML template columns and more, as you can see in the MSDN Library documentation.
是的。只需标记AutoGenerateColumns=False并手动定义您的列。您可以使用普通的文本绑定列、复选框列、自定义 XAML 模板列等,如您在MSDN 库文档中所见。
<DataGrid ItemsSource="{Binding DataSource}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="Simple Value"
Binding="{Binding SimpleValue}" Width="*" />
<DataGridTemplateColumn Width="*" Header="Complex Value">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBox Text="{Binding ComplexValue}"/>
<TextBox Text="{Binding ComplexValue2}"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
回答by Nikhil Agrawal
Yes, Yes very much. If your Table structure and Column Name remains constant then in Datagrid XAML set AutoGenerateColums = Falseand manually create all columns.
是的,是的,非常。如果您的表结构和列名保持不变,则在 Datagrid XAML 中设置AutoGenerateColums = False并手动创建所有列。
<dg:DataGrid Name="mydg" ItemsSource="{Binding Data}" AutoGenerateColumns="False">
<dg:DataGrid.Columns>
<dg:DataGridTextColumn Header="Col 0" Binding="{Binding FirstColumnName}" />
<dg:DataGridTextColumn Header="Col 1" Binding="{Binding SecondColumnName}" />
</dg:DataGrid.Columns>
</dg:DataGrid>
and then in codebehind simple provide Source like
然后在代码隐藏中简单地提供 Source 之类的
mydg.ItemSource = Data.DefaultView;
Now when your DataTable contains column FirstColumnNameand SecondColumnNamethey will be databound to your Datagrid.
现在,当您的 DataTable 包含列FirstColumnName并且SecondColumnName它们将数据绑定到您的 Datagrid 时。
回答by Stipo
Also, you can handle DataGrid.AutoGeneratingColumnevent and set e.Cancel= true for columns that you don't want to be shown. This way you don't have to manually define columns that you want to show.
此外,您可以处理DataGrid.AutoGeneratingColumn事件并为不想显示的列设置e.Cancel= true。这样您就不必手动定义要显示的列。

