Nested UserControl(s) throw "Property was already registered by"

I have this UserControl xaml:

<Grid>
        <Separator x:Name="sep" VerticalAlignment="Center" Height="10" />
</Grid>

and its code behind where I define a DependencyProperty to edit the line color:

public partial class SeparatorLineText : UserControl
    {
        public static DependencyProperty? ColorProperty;
        private PropertyMetadata meta = new PropertyMetadata(propertyChangedCallback: ColorChanged);
        public SeparatorLineText()
        {
            ColorProperty = DependencyProperty.Register("MyColor", 
                typeof(Brush), 
                typeof(SeparatorLineText), 
                meta);

            InitializeComponent();
        }

        public Brush MyColor
        {
            get { return (Brush)base.GetValue(ColorProperty); }
            set { base.SetValue(ColorProperty, value); }
        }

        private static void ColorChanged(object d, DependencyPropertyChangedEventArgs e)
        {
            ((SeparatorLineText)d).OnColorChanged(e);
        }

        protected virtual void OnColorChanged(DependencyPropertyChangedEventArgs e)
        {
            sep.Background = (Brush)e.NewValue;
        }
    }

Then I have this other UserControl which has SeparatorLineText inside:

<UserControl x:Class="MySubWindow" 
...
>

<Grid>
    <control:SeparatorLineText MyColor="Red"/>
</Grid>

Finally, in MainWindow.xaml I include MySubWindow which has SeparatorLineText inside:

<control:MySubWindow x:Name="MyTab" VerticalAlignment="Top" Width="1280"/>

When i run the project it displays my custom separator correctly, but in the MainWindow’s xaml designer it doesn’t load correctly saying: "MyColor property was already registered by SeparatorLineText"

I’ve already read the other topics about this but I didn’t find a solution.

>Solution :

Dependency properties only need to be registered once. In your situation it is registered every time the constructor is called. You can solve this with a static constructor:

public static DependencyProperty ColorProperty;

// You can also make this field static, since it is not bound to a specific instance.
private static PropertyMetadata meta = new PropertyMetadata(propertyChangedCallback: ColorChanged);

static SeparatorLineText()
{
    ColorProperty = DependencyProperty.Register("MyColor", 
        typeof(Brush), 
        typeof(SeparatorLineText), 
        meta);
}

public SeparatorLineText()
{
    InitializeComponent();
}

Or initialize it directly:

public static DependencyProperty ColorProperty = 
    DependencyProperty.Register("MyColor", 
        typeof(Brush), 
        typeof(SeparatorLineText), 
        meta);

// You can also make this field static, since it is not bound to a specific instance.
private static PropertyMetadata meta = new PropertyMetadata(propertyChangedCallback: ColorChanged);

public SeparatorLineText()
{
    InitializeComponent();
}

Leave a Reply