Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows 10 UWP UserControl with customizable content

Tags:

c#

uwp

I want to make a user control in Windows 10 UWP with changing content.

I know how to make a simple user control, but I need a user control like this:

<Controls:UserControl x:Name="Usercontrol1" Margin="0,10,0,0" Grid.Row="1">
    <Controls:UserControl.MainContent>
        <Grid x:Name="Content">
            //Items are here
        </Grid>
    </Controls:UserControl.MainContent>
</Controls:UserControl>

I have Grid in my user control that is empty and I want to give this grid different items in every page. I want a way to set a grid for my user control in the page, then add this grid to my user control instead of that empty grid.

Is there any way to do this?

like image 604
Amin Avatar asked Sep 04 '16 04:09

Amin


1 Answers

To do this, you need to create a MainContent dependency property in the code-behind of your user control and display it using a ContentPresenter.

Suppose your user control is defined in MyControl.xaml and MyControl.xaml.cs.

Creating the MainContent dependency property

Inside the UserControl class definition in UserControl.xaml.cs add the following:

public static readonly DependencyProperty MainContentProperty =
   DependencyProperty.Register( 
      "MainContent", 
      typeof( object ), 
      typeof( MyControl ), 
      new PropertyMetadata( default( object ) ) );

public object MainContent
{
    get { return ( object ) GetValue( MainContentProperty ); }
    set { SetValue( MainContentProperty, value ); }
}

As a shortcut in Visual Studio you can write propdp or dependencyProperty (depending on your version) and press the Tab key to automatically fill out a code snippet for the whole property.

Adding ContentPresenter

Inside the MyControl.xaml find the place where you want to display the content and put a ContentPresenter there with a binding to the MainContent property. There are several ways to do this.

The newest technique with x:Bind syntax

<ContentPresenter Content="{x:Bind MainContent}" />

Using binding with element - here you will need to add a x:Name attribute to the UserControl element itself, call it RootControl for example, and then create the binding like this:

<ContentPresenter Content="{Binding MainContent, ElementName=RootControl}" />

Using binding with DataContext - in the constructor of the UserControl in MyControl.xaml.cs you can set the DataContext - this.DataContext = this; and then write simply:

<ContentPresenter Content="{Binding MainContent}" />

Usage

Now your UserControl is ready and you can use it like this:

<local:MyControl>
  <local:MyControl.MainContent>
     <!-- some content :-) -->
     <Image Source="Assets/LockScreenLogo.png" Width="100"/>
  </local:MyControl.MainContent>
</local:MyControl>
like image 81
Martin Zikmund Avatar answered Nov 05 '22 17:11

Martin Zikmund