Romano Zumbé
Romano Zumbé

Reputation: 8089

Bind Control/Window property to custom property and set default value

I'm trying to bind the Title property of a Window to a custom property of this Window. The XAML looks like this:

Title="{Binding Path=WindowTitle, RelativeSource={RelativeSource Mode=Self}}"

The code behind like this:

public string WindowTitle
{
    get
    {
        string title = (string)GetValue(WindowTitleProperty);
        title = string.IsNullOrEmpty(title) ? "Editor" : title;
        return title;
    }

    set
    {
        SetValue(WindowTitleProperty, value);
    }
}

public static readonly DependencyProperty WindowTitleProperty =
           DependencyProperty.Register("WindowTitle", typeof(string), typeof(Editor), new UIPropertyMetadata(null));

This works good after the property WindowTitle was set to a new value. But unfortunately upon loading the Window I don't get any title. The getter of WindowTitle isn't even called. As far as I can say, it never gets called. What am I doing wrong? Why is the getter never called (even when the title is set correctly)? Can I set a defaultvalue on any other way?

Upvotes: 0

Views: 242

Answers (1)

mm8
mm8

Reputation: 169360

Your property looks strange. Why is it defined as a dependency property to begin with? You might as well use a CLR property and implement the INotifyPropertyChanged interface. This works fine for me:

public partial class Window13 : Window, INotifyPropertyChanged
{
    public Window13()
    {
        InitializeComponent();
    }

    private string _windowTitle = "default title...";
    public string WindowTitle
    {
        get { return _windowTitle; }
        set { _windowTitle = value; NotifyPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

The CLR getter of a dependency property should only call the GetValue method and not contain any other logic.

Edit: If you do want a dependency property for some reason, it should be implemented like this:

public string WindowTitle
{
    get
    {
        return (string)GetValue(WindowTitleProperty);
    }

    set
    {
        SetValue(WindowTitleProperty, value);
    }
}

public static readonly DependencyProperty WindowTitleProperty =
           DependencyProperty.Register("WindowTitle", typeof(string), typeof(Editor), new UIPropertyMetadata("Editor"));

Note that you specify the default value when you register the property.

Upvotes: 2

Related Questions