What's the difference betwen a UserControl and a ContentControl?
Asked Answered
C

6

23

According to all of the documentation, when you're creating a non-lookless control, you're supposed to subclass UserControl. However, UserControl is a simple subclass of ContentControl but it doesn't appear to add anything to it, interface-wise. As such, you can take that designer-generated code and change the base class to ContentControl and it appears to still work exactly the same.

So what's the point of UserControl over ContentControl?

Update:

For those who keep answering Visual Studio treats them differently, I'd argue that isn't the case. Try it! Create a new UserControl in Visual Studio, then in the resulting XAML file, change the root tag to ContentControl. Then in the associated class file, change the base class to ContentControl or simply delete it as I have done here (see the note) and you'll see it appears to work exactly the same, including full WYSIWYG designer support.

Note: You can delete the base class from the code-behind because it's actually a partial class with the other 'part' of the class being created by the XAML designer via code-generation. As such, the base class will always be defined as the root element of the XAML file, so you can simply omit it in the code-behind as it's redundant.

Here's the updated XAML...

<ContentControl x:Class="Playground.ComboTest.InlineTextEditor"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <TextBlock Text="Success" />

</ContentControl>

...and the associated class file...

namespace Playground.ComboTest {

    public partial class InlineTextEditor {

        public InlineTextEditor()
            => InitializeComponent();
    }
}
Caz answered 13/9, 2013 at 8:27 Comment(2)
The only thing that is different from ContentControl is that UserControl overrides the OnCreateAutomationPeer method, you might look for that. Maybe it has some different UI-behaviors than the ContentControl.Drumhead
You're almost right... it overrides a few other things as well (as shown in Reflector.) Still, you're the first person to comment on an actual difference between the two, so if you can put this in an answer, I'll mark yours as the accepted one.Caz
A
40

UserControls are a good fit for aggregating existing controls when you don't need to provide the consumer a ControlTemplate. This means that UserControls are not lookless. Why not just use ContentControl as it can have coupled XAML like a UserControl and the implementation looks similar to UserControl? Well, there are several important technical differences you must know:

  1. UserControls set themselves as the source to RoutedEvents raised by elements within them. This means that when an element outside the UserControl receives a bubbled event, the Source is the UserControl, not the thing you interacted within the UserControl. In the philosophical sense of what you often hear about UserControls, "It's for aggregating existing controls", this makes sense as you want the parent container element to think of your UserControl as a single unit. For example, your UserControl contains a button that the user clicks and the Grid that contains your UserControl instance receives the MouseLeftButtonUp event but the Button is not the Source of the event, your UserControl is.
  2. UserControl sets Focusable and IsTabStop to false. You can see the philosophy demonstrating itself again here as we don't want a grouping of existing controls to be Focusable.
  3. UserControl sets HorizontalAlignment and VerticalAlignment to Stretch. A ContentControl would automatically be set to Left and Top.
  4. UserControl's own AutomationPeer implementation allows you to change VisualStates via VisualStateManager.GoToState(). ContentControl requires the VisualStateGroups to be at the top-level and you must call them with VisualStateManager.GoToElementState().
  5. UserControl's own ControlTemplate wraps your content in a Border. This again makes sense when thinking of the philosophical use case for UserControl.
  6. UserControl's own ControlTemplate provides more TemplateBindings than ContentControl. This is kind of a recapitulation of some above items but explains how they are possible. Recall that UserControl provides a Border so that relates to some of these free TemplateBindings you see below. This enables respect for BorderBrush, BorderThickness, Background and Padding properties on your control that would otherwise not work with just a ContentControl. For example, if you just derive your control from ContentControl and set the Background property on the root ContentControl element it will not work because the ControlTemplate of ContentControl has no TemplateBinding for Background. Of course you could set the Background property on the child content element that wraps your desired elements, like a Grid, but that isn't ideal IMO.

ContentControl's ControlTemplate

<ControlTemplate TargetType="ContentControl">
  <ContentPresenter
   Content="{TemplateBinding ContentControl.Content}"
   ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
   ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}" />
</ControlTemplate>

UserControl's ControlTemplate

<ControlTemplate TargetType="UserControl">
  <Border BorderBrush="{TemplateBinding Border.BorderBrush}"
   BorderThickness="{TemplateBinding Border.BorderThickness}"
   Background="{TemplateBinding Panel.Background}"
   Padding="{TemplateBinding Control.Padding}"
   SnapToDevicePixels="True">
    <ContentPresenter
     HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
     VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
     SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"
     ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
     ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}"
     Content="{TemplateBinding ContentControl.Content}" />
  </Border>
</ControlTemplate>
Alvinalvina answered 18/1, 2017 at 14:41 Comment(4)
Finally a truly definitive answer, and with code too! Switching accepted to yours because of the depth of info it. Thanks for sharing! Very helpful stuff and clears a lot of things up for me, as I'm sure it will others too.Caz
To anyone wondering, you can inspect the a framework provided control's ControlTemplate via XamlPadX. It "ain't" pretty but it will let you look at the Default Styles of the framework controls and hence the variety of TemplateBindings provided.Alvinalvina
Just came back here again and I have to say this is still one of the best answers on SO. Truly definitive, yet easily digestible, and with examples. Thanks again for a truly excellent answer that I still reference regularly.Caz
I wish I stumbled across this answer several years ago...Announce
S
10

Basically, the UserControl class is there for convenience. It enables us to build little parts of the UI from already existing controls, whereas ContentControls are really for creating new controls, generally with a single purpose and/or functionality.

I read a book that had a good explanation of this and by good luck, someone has 'put a copy of it online'. From the linked book:

The UserControl class is a container class that acts as a “black box” container for a collection of related controls. If you need a set of three controls to always appear together and be allowed to easily talk to each other, then a likely candidate for making that happen is the UserControl class.

Then relating to whether to create a CustomControl:

The following is a summary of the decision process:

Use the framework as much as possible. WPF provides a variety of extensible controls, so make sure that the functionality you want doesn’t already exist in a WPF control.

In many cases, the data structure you’re working with requires different visual representation. Using ControlTemplates and DataTemplates can often get you the functionality you need.

Look at ValueConverters to see whether they can help bridge the gap between the stock functionality and what you need.

Finally, see whether you can’t extend existing behavior with attached properties.

Take a look for an in depth answer to your question:

WPF Control Development Unleashed

UPDATE >>>

@MarqueIV, to answer your question more directly: The UserControl class is provided to us for convenience. That's it. If you add a WPF CustomControl into your project, you will see that it has no XAML file. This means that you have to design you control markup in a file called Generic.xaml in the Themes folder. The UserControl class gives us a XAML file so that it is easier to create them... so it is more convenient... that's it. That's the reason.

Salverform answered 13/9, 2013 at 8:39 Comment(7)
I have that book, and have read it, but as I said above, you can still 'build little parts of the UI' with a ContentControl subclass. Try it yourself! Use VS to create a new UserControl, then in the XAML file, change the root element to ContentControl, and in the code-behind, change the base class to ContentControl. It works completely identically.Caz
Saying something is easier to create doesn't explain the difference. For instance, they could have very well made the UserControl template internally use a ContentControl, and as I have shown above, you can use a ContentControl with the designer. The real answer was brought up by @Florian GI above as a comment to the question in that UserControl overrides a few of the methods of ContentControl. Reflector confirmed his statements. So apparently there actually is a difference... internally. That's why I missed it.Caz
He wants to know the difference between UserControl and ContentControl, not UserControl and CustomControl. ;)Drumhead
Shoot... I need to get some glasses!Salverform
@Salverform Just read the question before answering it and you'll be fineBigwig
LOL... now now guys... play nice! Sheridan was just trying to help! So he was wrong! ;) Seriously though, @Sheridan, you've commented on a lot of my questions, so I for one thank you for your efforts. (Of course I'd thank you even more if you actually voted them up once in a while! Sheesh! What's a guy gotta do to get to 4K around here?! [smirk])Caz
@MarqueIV At least one thing is for sure, it's way easier to gain rep through questions than through answers -.-Drumhead
D
3

One thing that is different from ContentControl is that UserControl overrides the OnCreateAutomationPeer method, you might look for that. Maybe it has some different UI-behaviors than the ContentControl.

This method creates an UserControlAutomationPeer-instance.

Drumhead answered 13/9, 2013 at 9:5 Comment(1)
Thanks! :) Yours was the first that showed a definitive difference. While the interface is completely identical, Reflector confirmed that there are a few overrides going on in UserControl as you had stated.Caz
J
1

ContentControl
A ContentControl directly derives from Control class.
It hosts a single element which can be a container (eg Grid, Stackpanel, ...) hosting itself several elements (eg StackPanel with TextBlock and Image children).
Its appearance can be modified through a DataTemplate.
See MSDN Remarks section.

UserControl
A UserControl derives from ContentControl.
It does NOT support templates, thus no customization.
It does not catch focus automatically like a Window would.
Still in the MSDN Remarks section.

Jaclyn answered 4/11, 2016 at 16:28 Comment(1)
Since UserControl inherits from ContentControl, which in turn inherits from Control, it has both Template and ContentTemplate properties. Why not throw in a ContentPresenter or whatever? Not that the Content property of UserControl sees a lot of use in my experience, but it's there.Facetiae
I
0

UserControl is a composite control. It has similar concept with UserControl in ASP.NET Webforms. This means it's a control that is composed from many controls. In WPF, creating user control has supports for designer in Visual Studio 2008 and above. ContentControl is a control that is intended to have a single control as its content.

For more information: http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.aspx

Itinerancy answered 13/9, 2013 at 8:44 Comment(6)
Please see my just-added code examples. You can absolutely use ContentControl with the designer in VisualStudio. Try it! Create a new UserControl, then change the base class to ContentControl in the code-behind, and change the root tag of the XAML to ContentControl. It works exactly the same. UserControl is just what the template inserted, but it doesn't appear to have anything to do with designer functionality.Caz
You are right. But I didn't mention that ContentControl can't have designer support. As stated in MSDN Library, ContentControl is intended to contain a single control. This is why the concept is the same as UserControl in ASP.NET webforms.Itinerancy
I'm not sure why you keep saying that about a ContentControl because a UserControl too can only contain a single child. Why? Because a UserControl is a ContentControl! (Don't confuse the fact that the single control may itself have many children, such as a StackPanel. The UserControl still just has one.) And as for the designer support comment, that was because you said creating a UserControl has support in the designer, which a reader would take as it being implied a ContentControl doesn't, which it does with a little manual tweaking.Caz
And as for your ASP.NET comment, it's not the concept I'm questioning because you can implement the concept of a UserControl with a ContentControl (see above.) I was specifically asking about the differences between those two classes, which reflector calls out as the former overrides a few methods in the latter to change its default behavior, even though their interfaces are completely identical. Hope that all now makes sense.Caz
@MarqueIV I'm implying the ContentControl is for single type, based on MSDN Library documentation as is. Have you read it? I agree for your comment about ASP.NET, after you make clarification.Itinerancy
I'm gonna call you out on that again. ComboBox for instance is a ContentControl, but it is built up of several visual controls representing it. The difference is those constituents are applied via the Control's Template property whereas the constituent controls of a UserControl are set via the attached XAML file. That said, there's nothing stopping me from completely recreating the ComboBox exactly, but as a user control, which would mean it still meets your 'single type' criteria. So yes, I have read it. Thanks for asking. Again, the actual difference is in the marked answer.Caz
P
0

UserControl and ContentControl maybe the same implementation but the use case are not the same.

we need to answer two questions when to use UserControl or CustomControl? and when to use ContentControl?.

so when to use a UserControl or CustomControl?

Whenever I want to have a reusable piece of UI
for example if I want to have a FileDialogBrowser meaning a button with a TextBlock next to it so whenever i press the button and a user chooses a file i will show the chosen file in the TextBlock.

same but not exactly goes for customControl however here we want to do something more sophisticated, anyway this is not the issue.

so when to use ContentControl?

this is a little tricky to say but let's say we want to have progressBar with a message so we can inherit from BusyIndicator or Border, however if we use a ContentControl we have control which can Control the content inside it. we can have it wrapping around other xaml elements.

hope this helps

Peluso answered 10/6, 2014 at 20:0 Comment(1)
Thanks, but I'm looking for a technical difference, not a conceptual one. I just marked an answer which showed exactly that. Check it out! :)Caz

© 2022 - 2024 — McMap. All rights reserved.