// Create a class that implements INotifyPropertyChanged.
public class MyColors : INotifyPropertyChanged
{
private SolidColorBrush _Brush1;
// Declare the PropertyChanged event.
public event PropertyChangedEventHandler PropertyChanged;
// Create the property that will be the source of the binding.
public SolidColorBrush Brush1
{
get { return _Brush1; }
set
{
_Brush1 = value;
// Call NotifyPropertyChanged when the source property
// is updated.
NotifyPropertyChanged("Brush1");
}
}
// NotifyPropertyChanged will raise the PropertyChanged event,
// passing the source property that is being updated.
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
示例代码中MyColors类继承了INotifyPropertyChanged 接口,当Brush1属性更改时将触发PropertyChanged事件通知目标对象以及更改。
// Custom class implements the IValueConverter interface.
public class DateToStringConverter : IValueConverter
{
#region IValueConverter Members
// Define the Convert method to change a DateTime object to
// a month string.
public object Convert(object value, Type targetType,
object parameter, string language)
{
// value is the data from the source object.
DateTime thisdate = (DateTime)value;
int monthnum = thisdate.Month;
string month;
switch (monthnum)
{
case 1:
month = "January";
break;
case 2:
month = "February";
break;
default:
month = "Month not found";
break;
}
// Return the value to pass to the target.
return month;
}
// ConvertBack is not implemented for a OneWay binding.
public object ConvertBack(object value, Type targetType,
object parameter, string language)
{
throw new NotImplementedException();
}