Thursday, April 15, 2010

Creating a globally accessible property in a Silverlight application

You have created a Silverlight application and have a property that you want to make globally available. Although you could add it to the Resources collection of your App object, you really want to know every time the property has changed. If you were in a UserControl, you could create dependency properties that allow you to listen for PropertyChanged events, but these would not be global. Handling this at the application level would be best, but because App doesn’t derive from DependencyObject like UserControls, you cannot implement the SetValue and GetValue methods that are required for writing dependency properties.

It turns out that the solution ends up being easier than you think. Essentially you will be encapsulating an object within the App that implements INotifyPropertyChanged. You will then add PropertyChanged events anywhere you want to know where the property changes.

Steps:
1. Create a new Silverlight Application.
2. Add a new class that implements INotifyPropertyChanged. I will call mine “GroupNameObject”. Make sure to add a System.ComponentModel using statement.

using System.ComponentModel;

public class GroupNameObject : INotifyPropertyChanged
{
private string groupName;

public event PropertyChangedEventHandler PropertyChanged;

public GroupNameObject(string value)
{
this.groupName = value;
}

public string GroupName
{
get
{
return groupName;
}
set
{
groupName= value;
OnPropertyChanged("GroupName");
}
}

protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

3. In your App class add a public property of the type you just created.

public GroupNameObject GroupName = new GroupNameObject("Admin");

4. Now in any UserControl constructor, you can subscribe to the PropertyChanged event and add an event handler.

public MainPage()
{
InitializeComponent();
//Notice how App.Current can be cast to your App instance.
((App)App.Current).GroupName.PropertyChanged +=
new System.ComponentModel.PropertyChangedEventHandler(GroupName_PropertyChanged);
}

void GroupName_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
//Disable update button if group is viewer
if(((GroupameObject)sender).GroupName == “Viewer”)
{
updateButton.IsEnabled = false;
}

}

Now any time the property gets changed, you can listen to it and act accordingly. Obviously you would use an object or enum instead of a string here, but I kept it easy for illustration purposes. Also, if you are using MVVM, you should handle this in your ViewModel classes. Happy coding!

No comments:

Post a Comment