Search code examples
wpfxamldatatemplate

Where can I use a DataTemplate in something that isn't a repeater type of control?


Ok, I know it's kind of weird, but I am trying to create a data driven panel that reconfigures itself based on a DataTemplate member that I have on a object. Right now I am accomplishing this by using an ItemsControl bound against a dummy list of 1 bogus item so that I get a single instance of the data template. It just seems silly to have to do this in an ItemsControl, but I can't think of anything that will use my DataTemplate without trying to do it against a list of items. Anyone have any idea?

Just for clarity, let's say I have a Widget class:

public class Widget
{
   public string Name { get; set; }
   public DataTemplate MyTemplate { get; set; }

   public List<object> DummyList = new List<object> { new object(); } 
}

and the Xaml something like:

<ItemsControl ItemsSource={Binding DummyList} ItemTemplate={Binding MyTemplate}/>

I can then create a collection of Widgets and populate each one with the correct data template based on the object's status.

Anyway, as I said, this works... I'd just like to find a more elegant solution than using an ItemsControl if anyone knows of one.


Solution

  • Chances are that you could also just set ContentTemplate="{Binding template}" if your control (that you wish to dynamically modify its contents - e.g. Button inside etc.) is ContentControl. I found that often 'overlooked' as it's not immediately visible or intuitive, but saves you adding extra 'content'.

    Or you can use ContentControl - or presenter as suggested already.