A couple more bits of code that others might find useful... Whenever I do databinding-intensive apps (both Silverlight & WPF), I find myself writing a fair amount of boilerplate code. If you want change notifications on your class, you need to inherit from INotifyPropertyChanged, define a PropertyChanged event, and write a couple lines of code to fire it:
if (this.PropertyChanged!= null) { var args = new PropertyChangedEventArgs("SomeProperty"); PropertyChanged(this, args); }
Not rocket science, but it gets old after the 10th time. How about a ChangeableObject base class?:
public class ChangeableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { var args = new PropertyChangedEventArgs(info); PropertyChanged(this, args); } } }
Now you can inherit the PropertyChanged event, and simplify firing it to a single line, e.g.:
public class Elevator : ChangeableObject { private double position = 0; public double Position { get { return position; } set { position = value; NotifyPropertyChanged("Position"); } } }
Similarly, it never ceases to annoy me that whenever I write a value converter, I'm forced to define a a ConvertBack method even though I almost never use it. Plus, IntelliSense for implementing interfaces isn't as strong as overriding virtual methods... So here's a trivial base class:
public abstract class ValueConverter : IValueConverter { public abstract object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture);
public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new Exception("unsupported"); } }
Which can be used like this:
public class BoolToVisibilityConverter : ValueConverter { public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var v = (bool)value; var result = (v) ? Visibility.Visible : Visibility.Collapsed; return result; } }