Muckers Mucker
Muckers Mucker

Reputation: 109

Reusing User Controls

I'm trying to alter an existing WPF application and my lack of WPF experience (I'm WINFORMS) is making this difficult.

I've come across a situation where I need to reuse a UserControl and I'm not sure how to do this in terms of modifying the xaml. I'll explain.

UserControlA has the following code:

   <Grid Name="gdMain" Style="{StaticResource ContentRoot}">
        <content:MonitorAlarmsPage />
    </Grid>

Now, "MonitorAlarmsPage" is an AXML document that defines another UserControl - UserControlB. This UserControl, once created has to persist for the lifetime of the application.

So, I could have many UserControlAs, but only ONE UserControlB.

I've created a static class that has an appropriate UserControlB field which is updated when UserControlB is created, but how do I modify the content:MonitorAlarmsPage so that the content of the grid is replaced by the existing UserControlB as referenced in this static class and not by the XAML file that defines UserControlB? Can this actually be done? i.e. essentially, insert pre created user controls inside an XAML page.

To make things a bit clearer, UserControlB is essentially a page that can sit inside another page. The page is complex and there is a massive overhead incurred when it is created and so must only be created once.

Upvotes: 0

Views: 606

Answers (1)

Sheridan
Sheridan

Reputation: 69987

WPF is very different to WinForms, so you certainly have your work cut out for you. The basic idea for the solution to your problem is this. You'll need to add a DependencyProperty to the MonitorAlarmsPage control. This will enable you to data bind to this property from outside the control.. This property should be of a type of custom class that you define, that contains all of the properties required in the inner control.

The next stage is to develop a DataTemplate that defines how WPF should display your custom class when it comes across an instance of it. In this DataTemplate, you declare your inner control, so that when WPF sees the custom class, it displays the inner control and sets the custom class as the DataContext for the inner control:

<DataTemplate DataType="{x:Type YourXmlNamespacePrefix:YourCustomClass}">
    <YourControlsXmlNamespacePrefix:YourInnerControl DataContext="{Binding}" />
</DataTemplate>

Finally, you'll need to data bind your custom class (the static class) to the outer UserControl:

<content:MonitorAlarmsPage YourCustomClassProperty="{Binding YourStaticClass}" />

So just to be clear... this static class should be a data class, not a UI class. When using WPF, we manipulate data, not UI elements. We let the wonderful templating system generate the UI for us.

Upvotes: 1

Related Questions