Home > Software engineering >  WPF datagrid usercontrol binding
WPF datagrid usercontrol binding

Time:10-15

Is it possible to add the same usercontrol to datagrid column1 and column2? There is only one usercontrol.

<DataGrid SelectionUnit="Cell" Name="dataGrid" AutoGenerateColumns="False" CanUserAddRows="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <DataGrid.Columns>
            <DataGridTextColumn Header="test1" Binding="{Binding Name}"/>
            <DataGridTextColumn Header="test2" Binding="{Binding image1}"/>
            <DataGridTextColumn Header="test3" Binding="{Binding image2}"/>
            <DataGridTemplateColumn Header="column1">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <local:UcFrameLessSheetInfoListviewItem />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="column2">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate x:Name="test">
                        <local:UcFrameLessSheetInfoListviewItem />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

enter image description here

CodePudding user response:

To share the cell template, you have to declare it as a resource, in the grid, the user control or at the App level :

<UserControl.Resources>
    <DataTemplate x:Key="TestCellTemplate" DataType="viewModel:MyItemsType">
        <local:UcFrameLessSheetInfoListviewItem />
    </DataTemplate>
...
</UserControl.Resources>

Then you can reference it using StaticResource:

<DataGridTemplateColumn Header="column1" CellTemplate="{StaticResource TestCellTemplate}" />
<DataGridTemplateColumn Header="column2" CellTemplate="{StaticResource TestCellTemplate}" />
  • Related