Dynamically create a DataTempalte in Silverlight code.

The issue is following: we have a ListBox and for some reason we need to create a ListBox.ItemTemplate in code. In my case, I had to build a ListBox were each item is a button and I don’t know the template of it. I got it from other service. So there is no choose to do it on some other case, except of whole refactoring of architecture.

First of all, I’d like to maintain: don’t do it!
J It’s not a juke, there are lots of other possibility to avoid this situation, such as: use a converters/multy-converters, use predefined templates, eventually different styles for your ListBox. However, it’s not always possible.

First way: use a XamlLoader.

Just create necessary template like a string in code behind and load it

(DataTemplate) XamlReader.Load(“<DataTemplate>…</DataTemplate>”);

Note: don’t forget about necessary namespace. But in our case we don’t know what template we have.

Second way: use a ContentControl.

I used a ContentControl (I placed here a button with a DataTemplate) and Loaded event.

In test application I just loaded a ControlTemplate for button from Resources. Then added a button with click handler:

Eventually, this button I added like a DataTemplate to ListBoxItem.

Hope it’ll help.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s