Vaccano
Vaccano

Reputation: 82341

WPF - Create a UI object from a DataTemplate

This is very similar to this question I asked earlier. I am hoping to be clearer and get a different answser.

I have a Data Object (called MockUI). It has a data template (in app.xaml) like this:

<DataTemplate DataType="{x:Type local:MockWI}">
    <Button Content="{Binding Name}"/>
</DataTemplate>

In my code I want create a UI object that what the data template is. So I have myMockWI and I want to find out what template that would use and get the object it creates (in this case a button with the content set to myMockWI).

I have tried to just make a button:

Button myButton = new Button {Content = myMockWI}

but as you can probably guess, that creates the button then puts another button inside that button (because the data template is applied). How can I get one button only?

Upvotes: 5

Views: 2316

Answers (1)

Vaccano
Vaccano

Reputation: 82341

Turns out that I just needed to go up the UI tree a bit.

If I make a new ContentControl then it has no Look to it and takes on whatever the datatemplate is.

So my code changes from above to this:

ContentControl myControl = new ContentControl {Content = myMockWI};

Upvotes: 3

Related Questions