The default value type does not match the type of the property

C#WpfWpf Controls

C# Problem Overview


I have this class

public class Tooth
{
    public string Id {get;set;}
}

And this custrom control

public partial class ToothUI : UserControl
{
    public ToothUI()
    {
        InitializeComponent();
    }

    public Tooth Tooth
    {
        get { return (Tooth)GetValue(ToothProperty); }
        set
        {
            SetValue(ToothProperty, value);
            NombrePieza.Text =   value.Id.Replace("_",String.Empty);
        }
    }
    public static readonly DependencyProperty ToothProperty =
        DependencyProperty.Register("Tooth", typeof(Tooth), typeof(ToothUI), new PropertyMetadata(0)); 

}

My problem is after Add Tooth dependency property, this error happen

The default value type does not match the type of the property

What exactly this error mean? What is the current way to set this DP

C# Solutions


Solution 1 - C#

Default value for DP does not match your type.

Change

public static readonly DependencyProperty ToothProperty =
        DependencyProperty.Register("Tooth", typeof(Tooth), typeof(ToothUI),
                                         new PropertyMetadata(0));

to

public static readonly DependencyProperty ToothProperty =
        DependencyProperty.Register("Tooth", typeof(Tooth), typeof(ToothUI),
                                      new PropertyMetadata(default(Tooth)));

Or simply omit setting default value for your DP:

public static readonly DependencyProperty ToothProperty =
        DependencyProperty.Register("Tooth", typeof(Tooth), typeof(ToothUI));

Solution 2 - C#

I came here for the title of the question but my type was a decimal default value and i solved with this 0.0M https://msdn.microsoft.com/en-us/library/83fhsxwc.aspx

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJuan Pablo GomezView Question on Stackoverflow
Solution 1 - C#Rohit VatsView Answer on Stackoverflow
Solution 2 - C#dpinedaView Answer on Stackoverflow