Zev Spitz
Zev Spitz

Reputation: 15377

XAML base class: user control, vs other control

What are the benefits and downsides of implementing a custom control in XAML by inheriting from UserControl:

<UserControl x:Class="MyButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Button>
    <!-- custom content here -->
    <!-- custom behaviors in the code behind -->
  </Button>
</UserControl>

vs inheriting from the control I'm putting inside the UserControl?

<Button x:Class="MyButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!-- custom content here -->
    <!-- custom behaviors in the code behind -->
</Button>

Upvotes: 0

Views: 112

Answers (1)

Sheridan
Sheridan

Reputation: 69987

There is no benefit to using a UserControl if you really want a Button. A UserControl just provides a simple way to create a control. From the UserControl Class page on MSDN:

If you do need to create a new control, the simplest way is to create a class that derives from UserControl. Before you do so, consider that your control will not support templates and therefore will not support complex customization. However, deriving from UserControl is a suitable model if you want to build your control by adding existing elements to it, similar to how you build an application, and if you do not need to support complex customization. (If you want to use templates with your control, derive from Control instead.)

As the remarks from MSDN note, using UserControl instead of Button as your base class will mean that your control cannot be templated, whereas when using a Button as the base class, you could still provide a new ControlTemplate.

You should always use the control that most closely suits your needs as the base class. The UserControl is only there to provide an easy way for us to add a collection of already existing controls to the UI. If that is not what you want to do, then don't use it.

Upvotes: 1

Related Questions