Shaku
Shaku

Reputation: 670

WPF DependencyProperty Usage

I'm having difficulty getting Dependency Properties to work without causing compilation errors.

I have a usercontrol called TitleBar which contains this DependencyProperty:

public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(TitleBar), new PropertyMetadata(false));

    public string Title
    {
        get
        {
            return (string)GetValue(TitleProperty);
        }
        set
        {
            SetValue(TitleProperty, value);
        }
    }

And on my view, in xaml:

<Components:TitleBar x:Name="customTitleBar" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3"/>

Which causes a designer/compilation error:

Cannot create an instance of "TitleBar". ... The invocation of the constructor on type 'TitleBar' that matches the specified binding constraints threw an exception. System.Exception {System.Windows.Markup.XamlParseException}

The usercontrol works perfectly without the DP on it. What am I doing wrong?

Strange thing is, when I actually put the Title="..." property into the xaml, it works in the designer until I try to compile it. From that point on, it gives me the mentioned error.

Upvotes: 0

Views: 236

Answers (2)

dkozl
dkozl

Reputation: 33384

Your DependencyProperty is a string yet in PropertyMetadata you specify default value as false

Upvotes: 2

kcnygaard
kcnygaard

Reputation: 814

You have specified the default value as bool when the property type is string.

Change

new PropertyMetadata(false)

to

new PropertyMetadata(null)

Upvotes: 2

Related Questions