本文共 3440 字,大约阅读时间需要 11 分钟。
MyColors textcolor = new MyColors();
textcolor.Brush1 = new SolidColorBrush(Colors.Red);
MyTextBox.DataContext = textcolor;
// 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));
}
}
}
// 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();
}
#endregion
}
<UserControl.Resources>
<local:DateToStringConverter x:Key="Converter1"/>
</UserControl.Resources>
...
<TextBlock Grid.Column="0"
Text="{Binding Month, Converter={StaticResource Converter1}}"/>
方案 | C# |
绑定到对象 | 可以为任何对象 |
从绑定对象中获取属性更改更新 | 数据对象必须实现 接口 |
绑定到集合 | 使用 |
从绑定集合中获取集合更改更新 | 使用 |
实现支持绑定的集合 | 扩展 或实现 、 (属于 )、 或 (属于 Object )。绑定到通用 IList(Of T) 和 IEnumerable(Of T) 的操作不受支持 |
实现支持集合更改更新的集合 | 扩展 或实现(非通用) 和 |
实现支持增量加载的集合 | 扩展 或实现(非通用) 和 。此外,还实现 |