locked
Using DataTemplate with dynamic amount of UserControls

    Question

  • Hi,

    I have this xaml:

    <Hub x:Name="hubxaml" Header="My Game menu">
    	<HubSection x:Name="hs0xaml">	
    		<DataTemplate x:Name="dtxaml" >
    			<StackPanel x:Name="spxaml">
    			</StackPanel>
    		</DataTemplate>
    	</HubSection>
    </Hub>

    I would like to add a dynamic range of user Controls using C# code behind to the stackpanel, but I understand nothing how to accomplish this. Some concrete code would be preferable.

    BR /Magnus

    Saturday, September 06, 2014 10:03 AM

Answers

  • Hi Flowhill,

    We can use XamlReader.Load method to create xaml from string in code-behind and then bind it to HubSection. Code looks like below.

    XAML:

     

     <HubSection Header="Section 5" x:Name="hub5">
    
                </HubSection>
    

    C#:

        StringBuilder sb = new StringBuilder();
    
                Random rnd = new Random();
    
                sb.Append("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">");
    
                sb.Append("<Grid Width=\"200\" Height=\"100\">");
    
                sb.Append("<StackPanel>");
    
                sb.Append("<TextBlock>"+rnd.Next(0,101).ToString()+"</TextBlock>");
    
                sb.Append("<TextBlock>" + rnd.Next(0, 101).ToString() + "</TextBlock>");
    
                sb.Append("<TextBlock>" + rnd.Next(0, 101).ToString() + "</TextBlock>");
    
                sb.Append("<TextBlock>" + rnd.Next(0, 101).ToString() + "</TextBlock>");
    
                sb.Append("<TextBlock>" + rnd.Next(0, 101).ToString() + "</TextBlock>");
    
                sb.Append("<TextBlock>" + rnd.Next(0, 101).ToString() + "</TextBlock>");
    
                sb.Append("</StackPanel>");
    
                sb.Append("</Grid>");
    
                sb.Append("</DataTemplate>");
    
                DataTemplate datatemplate = (DataTemplate)XamlReader.Load(sb.ToString());
    
                hub5.ContentTemplate = datatemplate;
    

    You can also see a good sample from MSDN, refer to http://code.msdn.microsoft.com/windowsapps/How-to-dynamically-875a548e.

    Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. <br/> Click <a href="http://support.microsoft.com/common/survey.aspx?showpage=1&scid=sw%3Ben%3B3559&theme=tech"> HERE</a> to participate the survey.

    Monday, September 08, 2014 2:14 AM
    Moderator