C#, Silverlight, XAML

Binding to Page Title in Silverlight

In SL4, the title of a page in a Silverlight navigation project is not implemented as a depenency property. You can’t bind the title of a page from a view model directly to it. While this article was a great starting point, the first 2 examples did not work for me.

I implemented a dependency property to handle it. Gets to the property may not work well, but its purpose is to set the page title, so that should not matter.

///

/// This allows a page title in a Silverlight Navigation application to be bound to.
/// Silverlight page titles are not DPs so they cannot be bound by normal means.
/// This replaces the event used in codebehind called OnDataLoaded, whose only
/// purpose was to set the page title.
/// Taken & Modified from http://forums.silverlight.net/forums/p/97849/223734.aspx
///

public class PageTitleBindingHelper : FrameworkElement //, INotifyPropertyChanged
{

public string PageTitle
{
get { return (string)GetValue(PageTitleProperty); }
set { SetValue(PageTitleProperty, value); }
}

// Using a DependencyProperty as the backing store for PageTitleProperty. This enables animation, styling, binding, etc...
public static DependencyProperty PageTitleProperty;

public PageTitleBindingHelper()
{
PageTitleProperty = DependencyProperty.Register("PageTitleProperty", typeof(string), typeof(PageTitleBindingHelper), new PropertyMetadata("", new PropertyChangedCallback(PageTitleChanged)));
}

private void PageTitleChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
HtmlPage.Document.SetProperty("title", e.NewValue);

Page p = App.Window.ContentFrame.Content as Page;
if (p != null)
p.Title = (string)e.NewValue;

//NotifyPropertyChanged("PageTitle");
}
}

To use: Place an instance in your page resources and bind the PageTitle property to whatever property is on your view model.

EDIT: HtmlPage seemed to crash randomly for other users of my app, so I’ve changed this. I have a reference to my main window available from the App class, where I was using it to hide parts of the UI for a kiosk, etc. I use that and figure out what page I am on, and set the title that way. It may not be the cleanest solution, but I will revisit this once I have some spare time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s