Click here to Skip to main content
15,916,371 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi guys,

I have a WPF code as below :

VB
<UserControl x:Class="Sample"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:view="Sample.view"
             xmlns:viewModel="Sample.viewModel"
             Width="auto" VerticalAlignment="Top">


XML
<UserControl.Resources>
    <DataTemplate DataType="{x:Type viewModel:SelectionViewModel}">
        <view:Transaction />
    </DataTemplate>
    <DataTemplate DataType="{x:Type viewModel:ConfigurationViewModel}">
        <view:Configuration />
    </DataTemplate>
</UserControl.Resources>

</UserControl>


I would like to add Those DataTemplates into Resources Programatically in Code behind.

My query is how to create data template programatically and how to add it into resoruces in code behind?

Thanks :)
Posted
Updated 20-May-11 21:10pm
v2

1 solution

According to the SDK, the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the XamlReader.Load() method. Believe me, that's the easiest way. It's very easy to build the necessary xaml string dynamically, and then load it.

To add the template to your Resources, you probably should create a ResourceDictionary with your template in it, use XamlReader.Load to load the xaml, and then merge the dictionary, like so.

C#
this.Resources.MergedDictionaries.Add(myResourceDictionary); 
 
Share this answer
 
Comments
Sanjay J Patolia 21-May-11 3:09am    
Thanks but I would to do it using Resource Dictionaty I tried but I am not able to get it in right way
#realJSOP 21-May-11 5:32am    
Well then, google is your friend, but I think you're going to find that this is the easiest way.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900