Search code examples
wpfmergedatatemplate

How to merge content of enduser defined to DataTemplate in WPF, some like change DataTemplate content at runtime


I want to change DataTemplate's content at runtime, the content is designed by enduser, and saved in a file as xaml format.

the DataTemplate is defined like this:

<DataTemplate x:Key="DataTemplate1">
    <Grid>
        <Canvas x:Name="canvas1" />
    </Grid>
</DataTemplate>

and the content designed by enduser like this:

<Canvas x:Name="canvas1">
    <Label ...>
    ...
</Canvas>

I want to meger the content designed by enduser to the datatemplate using code:

DataTemplate templateObj = FindResource("DataTemplate1");

and now I don't know how to change the templateObj to merge the content, at last the templateObj will like this:

    <DataTemplate x:Key="DataTemplate1">
        <Grid>
            <Canvas x:Name="canvas1">
                <Label ...>
                ...
            </Canvas>
        </Grid>
    </DataTemplate>

Solution

  • Actually I don't think you can marge two DataTemplates. Try create one parent template and one child which base on parent template. Change template use:

    DataTemplate summary = this.FindResource("SimpleTemplate") as DataTemplate;
    YourControl.ItemTemplate = summary;