开发者

How to copy existing column and insert it into datagrid?

I currently have a datagrid that contains a unique context menu for each column.. sample xaml is as follows:

  <DataGrid.ColumnHeaderStyle>
        <Style TargetType="DataGridColumnHeader">
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="ContextMenu" Value="{StaticResource default_columnHeaderMenu}" />
        </Style>
    </DataGrid.ColumnHeaderStyle>
    <DataGrid.Columns>
        <DataGridTextColumn Header="Person" Binding="{Binding Path=PersonID}" CellStyle="{StaticResource CenterAlignedCellStyle}" />

....

Inside the context menu, I have an item called "Insert column" which then contains a list of columns like so:

开发者_Python百科       <ContextMenu  x:Key="default_columnHeaderMenu" Name="defaultColumnHeaderMenu">
            <MenuItem Header="Insert Column" >
                <MenuItem Header="Person ID" Click="addColumn"/>
                <MenuItem Header="Health" />
                <MenuItem Header="Person Description" />
                <MenuItem Header="Person Age" />

.....

MY question is, using the column header context menus, what is the easiest way to add or duplicate these columns into my data grid ? (I'm not looking for a brand new, empty column, but some kind of "copy" of an already exiting column w/ the same data, etc.)

Using DataGrid.Columns, is there a way to some how find an index of a column based on the header name ?

Thanks for any help / suggestions.


You could define your columns as non-shared resources:

<DataGridTextColumn x:Key="PersonColumn" x:Shared="False" Header="Person" Binding="{Binding Path=PersonID}" CellStyle="{StaticResource CenterAlignedCellStyle}" />

Then in the menu item event you can retrieve it and add it to the DataGrid:

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    var col = FindResource("PersonColumn") as DataGridTemplateColumn;
    dataGrid.Columns.Add(col);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜