双向数据绑定,Silverlight和自定义控件/依赖项属性
问题描述:
如果我在需要IEnumerable<T>
的自定义控件上创建依赖项属性。双向数据绑定,Silverlight和自定义控件/依赖项属性
例如与IEnumerable<string>
:
public static readonly DependencyProperty MyCollectionProperty =
DependencyProperty.Register("MyCollection", typeof(IEnumerable<string>), typeof(MyControl), new PropertyMetadata(new List<string>()));
public IEnumerable<string> MyCollection
{
get { return (IEnumerable<string>)GetValue(MyCollectionProperty); }
set { SetValue(MyCollectionProperty, value); }
}
如果我在这种情况下它的数据绑定或ObservableCollection<T>
<string>
。 Silverlight是否为我处理双向数据绑定?
答
从MSDN“特别是,如果您使用的是OneWay或TwoWay(例如,当源属性动态更改时希望更新UI),则必须实施适当的属性更改通知机制,例如INotifyPropertyChanged接口”
ObservableCollection<T>
为您实现INotifyPropertyChanged。 IEnumerable<T>
不。如果您想要简单的双向绑定,只需绑定到ObservableCollection<T>
,并将您的UpdateSourceTrigger
更改为PropertyChanged
。 XAML:
<ItemSource = "{Binding Path=MyCollection, UpdateSourceTrigger=PropertyChanged}">
您能澄清一下您'为我管理双向数据绑定'吗?一般来说,双向绑定到集合并不是一个好主意。如果你只是操纵现有的集合,那么单向绑定工作正常。 – Stephan 2010-10-25 16:12:06