0

I have created a custom User Control from a Gruopbox. However, in order to be used as a container in a view, I must create a DependecyProperty for the Content. This results in an Unhandled Exception has occurred error in VS2017.

Picture of the error

This however, only happens when I bind the Content attribute in the gruopbox to my new Property.

<UserControl
    x:Class="Infrastructure.Controls.GroupBox.CollectionBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Name="Form"
    d:DesignHeight="450"
    d:DesignWidth="800"
    mc:Ignorable="d">

    <GroupBox Content="{Binding Content, ElementName=Form}"/>

</UserControl>

With the code behind being

public new object Content
    {
        get => (object)GetValue(ContentProperty);
        set => SetValue(ContentProperty, value);
    }
public new static readonly DependencyProperty ContentProperty = DependencyProperty.Register(nameof(Content), typeof(object), typeof(CollectionBox), new PropertyMetadata(null));

I tried using FalloutValue in the Binding to other controls as I assumed the designer didn't know what to put inside the container. Nevertheless, the error keeps occurring.

In runtime and in the view Designer the control looks and works fine. It is just in its designer that I can not see it.

Thanks.

Community
  • 1
  • 1
Albert Alonso
  • 656
  • 1
  • 6
  • 21
  • Why don't you simply create a `GroupBox` instead of a `UserControl` that contains a `GroupBox`? Change the root element in your XAML and the base class of the code-behind class from `UserControl` to `GroupBox`. – mm8 Mar 20 '19 at 14:19
  • @mm8 The exemple is a simplification of the control, as I have found that the error happens due to that Binding. By this I mean that the `GroupBox` is inside another container with other controls. – Albert Alonso Mar 20 '19 at 14:22
  • 1
    What if you create a custom template for the `UserControl`? – mm8 Mar 20 '19 at 14:23
  • And how would that solve the content binding? – Albert Alonso Mar 20 '19 at 14:27
  • 1
    You don't need to bind. You simply include a `` in the template. – mm8 Mar 20 '19 at 14:28

1 Answers1

1

You don't need another Content property, just another ControlTemplate, that defines the visual structure of your control, including the GroupBox that binds to the control's Content:

<UserControl x:Class="Infrastructure.Controls.GroupBox.CollectionBox" ...>
    <UserControl.Template>
        <ControlTemplate TargetType="UserControl">
            <Border> <!-- or any other control(s) here -->
                <GroupBox Content="{TemplateBinding Content}"/>
            </Border>
        </ControlTemplate>
    </UserControl.Template>
</UserControl>
Clemens
  • 123,504
  • 12
  • 155
  • 268