简体   繁体   中英

Two-way databinding, Silverlight and custom control / dependancy property

If I create an dependency property on a custom control that takes an IEnumerable<T> .

For example with an 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); }
}

If I databind an ObservableCollection<T> or <string> in this case to it. Does Silverlight take care of the two-way databinding for me?

From MSDN "In particular, if you are using OneWay or TwoWay (for example, you want your UI to update when the source properties change dynamically), you must implement a suitable property changed notification mechanism such as the INotifyPropertyChanged interface"

ObservableCollection<T> implements INotifyPropertyChanged for you. IEnumerable<T> does not. If you want easy two way binding simply bind to an ObservableCollection<T> , and change your UpdateSourceTrigger to PropertyChanged . XAML:

<ItemSource = "{Binding Path=MyCollection, UpdateSourceTrigger=PropertyChanged}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM