在 XAML-WPF 中设置列标题名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13952804/
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
Set Column Header Name in XAML- WPF
提问by Indhi
I would like to set the user defined column Header in a WPF datagrid that is bound to a database.
我想在绑定到数据库的 WPF 数据网格中设置用户定义的列标题。
for displaying ServerID, EventlogID I would like to display as Server, Event Log in the column header.
为了显示 ServerID, EventlogID 我想在列标题中显示为 Server, Event Log。
I have tried these already ...
我已经试过这些了......
<DataGrid x:Name="dataGrid1" ItemsSource="{Binding}" AutoGenerateColumns="True" >
<DataGrid.Columns>
<DataGridTextColumn Header="Server" Width="Auto" IsReadOnly="True" Binding="{Binding Path=ServerID}" />
<DataGridTextColumn Header="Event Log" Width="Auto" IsReadOnly="True" Binding="{Binding Path=EventLogID}" />
</DataGrid.Columns>
</DataGrid>
This works fine, and it changes the Column Header and the datas are also displayed.
这工作正常,它会更改列标题,并且还会显示数据。
But my problem it is displayed twice as first two column header from XAML and other two column header from the DB.
但我的问题是它作为 XAML 的前两列标题和数据库中的其他两列标题显示两次。
|Server|Event Log|ServerID|EventLogID|
how to overcome this replication ? Kindly help !
如何克服这种复制?请帮助!
回答by Louis Kottmann
That's because you left the AutoGenerateColumns="True"remove it, and there will be no more duplication.
那是因为你AutoGenerateColumns="True"把它去掉了,就不会再有重复了。
You're currently adding the columns once, automatically, and then a second time, manually!
您当前正在自动添加列一次,然后手动添加第二次!
回答by Arsen Ablaev
XAML: Add AutoGeneratingColumn="OnAutoGeneratingColumn"event to DataGridevement:
XAML:AutoGeneratingColumn="OnAutoGeneratingColumn"向DataGridevement添加事件:
<DataGrid x:Name="dataGrid1" ItemsSource="{Binding YourItems}" AutoGenerateColumns="True" AutoGeneratingColumn="OnAutoGeneratingColumn">
Code Behind: Add event handler as following:
代码隐藏:添加事件处理程序如下:
private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
switch (e.Column.Header)
{
case "ServerID":
e.Column.Header = "Server";
break;
case "EventID":
e.Column.Header = "Event";
break;
default:
e.Cancel = true;
break;
}
}

