views:

274

answers:

1

XAML:

<navigation:Page ... Title="{Binding Name}">

C#

public TablePage()
{
    this.DataContext = new Table() 
    { 
        Name = "Finding Table"
    };
    InitializeComponent();
}

Getting a ag_e_parser_bad_property_value error in InitializeComponent at the point where the title binding is happening. I've tried adding static text which works fine. If I use binding anywhere else eg:

<TextBlock Text="{Binding Name}"/>

This doesn't work either.

I'm guessing it's complaining because the DataContext object isn't set but if I put in a break point before the InitializeComponent I can confirm it is populated and the Name property is set.

Any ideas?

+2  A: 

You can only use data binding on properties that are supported by DependencyProperty. If you take a look at the docs for TextBlock for example you will find that the Text property has a matching TextProperty public static field of type DependencyProperty.

If you look at the docs for Page you will find that there is no TitleProperty defined, the Title property is therefore not a dependency property.

Edit

There is no way to "override" this however you could create an attached property:-

public static class Helper
{
    #region public attached string Title
    public static string GetTitle(Page element)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        return element.GetValue(TitleProperty) as string;
    }

    public static void SetTitle(Page element, string value)
    {
        if (element == null)
        {
            throw new ArgumentNullException("element");
        }
        element.SetValue(TitleProperty, value);
    }

    public static readonly DependencyProperty TitleProperty =
            DependencyProperty.RegisterAttached(
                    "Title",
                    typeof(string),
                    typeof(Helper),
                    new PropertyMetadata(null, OnTitlePropertyChanged));

    private static void OnTitlePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Page source = d as Page;
        source.Title = e.NewValue as string;
    }
    #endregion public attached string Title

}

Now your page xaml might look a bit like:-

<navigation:Page ...
    xmlns:local="clr-namespace:SilverlightApplication1"
    local:Helper.Title="{Binding Name}">
AnthonyWJones
ah I see. I assume there is no way to override this?
zXynK
@zXynK: An attached property would probably work in your case, edit answer to show how that is done.
AnthonyWJones
Thanks for your help.
zXynK