WPF - Creating a User Interface Object from a DataTemplate

This is very similar to the question I mentioned earlier. I hope to be clearer and get another defendant.

I have a data object (called MockUI). It has a data template (in app.xaml) as follows:

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

In my code, I want to create a user interface object that matches a data pattern. Therefore, I have myMockWI, and I want to find out which template to use and get the created object (in this case, the button with the content installed in myMockWI).

I tried just making a button:

Button myButton = new Button {Content = myMockWI}

but, as you can probably guess, this creates a button and then places another button inside that button (since the data template is applied). How can I get only one button?

+3
source share
1 answer

Turns out I just need to get a little closer to the UI tree.

If I create a new ContentControl, then it has no look at it and takes care of everything in the datatemplate.

So my code changes from above to:

ContentControl myControl = new ContentControl {Content = myMockWI};
+2
source

Source: https://habr.com/ru/post/1730965/


All Articles