如何将UI元素与数据进行绑定
<TextBox x:Name="MyTextBox" Text="Text" Foreground="{Binding Brush1, Mode=OneWay}"/>
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#
|
绑定到对象
|
可以为任何对象
|
从绑定对象中获取属性更改更新
|
|
绑定到集合
|
|
从绑定集合中获取集合更改更新
|
|
实现支持绑定的集合
|
扩展 List(Of T) 或实现 IList、IList(属于 Object)、IEnumerable 或 IEnumerable(属于 Object)。绑定到通用 IList(Of T) 和 IEnumerable(Of T) 的操作不受支持
|
实现支持集合更改更新的集合
|
|
实现支持增量加载的集合
|
扩展 ObservableCollection(Of T) 或实现(非通用)IList 和 INotifyCollectionChanged。此外,还实现ISupportIncrementalLoading
|