I have a user control in WPF that has a binding to a Dependency Property. When I try to compile the app, I get a "Property Name" was already registered by "ControlName" error, and the designer shows a "Cannot create an instance of "User Control" error.
Here is what my simple control looks like:
ExampleUserControl.xaml:
<UserControl x:Class="ExampleApp1.ExampleUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ExampleApp1"
mc:Ignorable="d" >
<TextBox Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:ExampleUserControl}}, Path=SomeStringValue}" />
</UserControl>
ExampleUserControl.xaml.cs:
public partial class ExampleUserControl : UserControl
{
public DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl));
public string SomeStringValue
{
get
{
return GetValue(SomeStringValueProperty) as string;
}
set
{
SetValue(SomeStringValueProperty, value);
}
}
public ExampleUserControl()
{
InitializeComponent();
}
}
The Main Window it's hosted in:
<Window x:Class="ExampleApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ExampleApp1"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<local:ExampleUserControl SomeStringValue="Test 1" />
<local:ExampleUserControl SomeStringValue="Test 2" />
</StackPanel>
</Window>
Here is what the designer looks like:
Here is what the XAML designer looks like:
What's happening is the Dependency Property is getting Registered multiple times under the same name and owner. Dependency Properties are intended to have a single owner, and should be statically instanced. If you don't statically instance them, an attempt will be made to register them for each instance of the control.
Make your DependencyProperty declaration static. Change it from:
public DependencyProperty SomeStringValueProperty =
DependencyProperty.Register("SomeStringValue",
typeof(string),
typeof(ExampleUserControl));
To:
public static DependencyProperty SomeStringValueProperty =
DependencyProperty.Register("SomeStringValue",
typeof(string),
typeof(ExampleUserControl));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With