我的问题似乎很简单:
一个人怎么可以添加自定义页眉到数据绑定DataGrid的WPF中?
How can one add custom headers to a data bound DataGrid in WPF?
我为什么要问这个问题?嗯,因为我装我的DataGrid有一个动态的ItemsSource(这是在$ C $生成的C-后面),绑定到IEnumerable的名单。这工作完全正常,虽然它使用属性名称作为列标题。
Why am I asking this question? Well, because I've fitted my DataGrid (which is generated in code-behind) with a dynamic itemssource, bound to an ienumerable 'list'. This works perfectly fine, although it uses the property names as column headers.
要提高可读性,我只是想指定自定义页眉进行分栏,但是...我的想法是与已经定义的列提供一个数据网格,并让ItemsSource的填补行。但是的ItemsSource处理与行,以及列
To improve readability I simply want to assign custom headers to the columns, however... My idea was to supply a datagrid with the columns already defined, and let the itemssource fill the rows. But itemssource deals with the rows, as well as the columns.
我希望你能在这里看到我的问题。帮助是极大的AP preciated!
I hope you can see my problem here. Help is greatly appreciated!
推荐答案DataGrid类具有配置列生成行为的属性,称为的AutoGenerateColumns(链接)。要禁用此行为,只是将其设置为false。
The DataGrid class has a property to configure the column generation behavior, called "AutoGenerateColumns" (link). To disable this behavior just set it to false.
你有你的DataGrid的形状更好地控制,如果你在XAML中做到这一点。举个例子:
You have a better control of the shape of your DataGrid if you do it in xaml. An example:
<Window x:Class="WpfApplication1.MainWindow" xmlns="schemas.microsoft/winfx/2006/xaml/presentation" xmlns:x="schemas.microsoft/winfx/2006/xaml" xmlns:i="schemas.microsoft/expression/2010/interactivity" xmlns:local="clr-namespace:WpfApplication1" Title="MainWindow" Width="525" Height="350"> <Grid> <DataGrid AutoGenerateColumns="False" > <DataGrid.Columns> <DataGridTextColumn Header="MyHeader1" Binding="{Binding MyProperty1}"/> <DataGridTextColumn Binding="{Binding MyProperty2}"> <DataGridTextColumn.Header> <Button Content="A button"/> </DataGridTextColumn.Header> </DataGridTextColumn> </DataGrid.Columns> </DataGrid> </Grid>
正如你所看到的,一列定义的标题属性将接受任何内容,文字或控件,如果您想进一步自定义它。
As you can see, the "Header" property of a column definition will accept any content, texts or controls, if you want to customize it further.
修改
如何从code做的背后,在窗口的Loaded事件的一个例子:
An example of how to do it from the code behind, in the Window's Loaded event:
void MainWindow_Loaded(object sender, RoutedEventArgs e) { var dataGrid = new DataGrid(); dataGrid.AutoGenerateColumns = false; // For each column you want var column1 = new DataGridTextColumn(); column1.Header = "MyHeader"; column1.Binding = new Binding("MyProperty"); dataGrid.Columns.Add(column1); // LayoutRoot is the main grid of the Window this.LayoutRoot.Children.Add(dataGrid); // Let's test to see if the binding is working IEnumerable<DummyClass> testEnumerable = new List<DummyClass>(){ new DummyClass(){MyProperty= "Element1"}, new DummyClass(){MyProperty= "Element2"}, }; dataGrid.ItemsSource = testEnumerable; }更多推荐
数据绑定的DataGrid自定义列标题
发布评论