I do not know how much it will help you, but because in most cases, the ObservableCollection<T> acts as a data source, we can use this, so we do the following:
1) In the user control create DP .
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable<object>), typeof(MyUserControl), new PropertyMetadatadefault(IEnumerable<object>))); public IEnumerable<object> ItemsSource { get { return (IEnumerable<object>)GetValue(ItemsSourceProperty); } set { SetValue(ItemsSourceProperty, value); } }
2) In the controller constructor, we subscribe to change the value of your DP .
public MyUserControl() { InitializeComponent(); var dp = DependencyPropertyDescriptor.FromProperty(ItemsSourceProperty, typeof(MyUserControl)); dp?.AddValueChanged(this, Handler); }
3) In the handler for a DP change, we INotifyCollectionChanged your property to INotifyCollectionChanged and subscribe to collection change notifications.
private void Handler(object sender, EventArgs eventArgs) { var nc = ItemsSource as INotifyCollectionChanged; if (nc != null) nc.CollectionChanged += OnCollectionChanged; }
4) Next, we implement your logic that reacts to changes in the collection:
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { // ΠΠ°ΡΠ° Π»ΠΎΠ³ΠΈΠΊΠ° Π½Π° ΡΠ΅Π°ΠΊΡΠΈΡ ΠΎΠ± ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠΈ ΡΠ²ΠΎΠΉΡΡΠ²Π° }
All entirely:
public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); var dp = DependencyPropertyDescriptor.FromProperty(ItemsSourceProperty, typeof(MyUserControl)); dp?.AddValueChanged(this, Handler); } private void Handler(object sender, EventArgs eventArgs) { var nc = ItemsSource as INotifyCollectionChanged; if (nc != null) nc.CollectionChanged += OnCollectionChanged; } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { // ΠΠ°Ρ ΠΊΠΎΠ΄ } public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register( "ItemsSource", typeof(IEnumerable<object>), typeof(MyUserControl), new PropertyMetadata(default(IEnumerable<object>))); public IEnumerable<object> ItemsSource { get { return (IEnumerable<object>)GetValue(ItemsSourceProperty); } set { SetValue(ItemsSourceProperty, value); } } }
ItemsPropertypropertyItemsPropertyelementItemsPropertyto this, i.e. displayed that the data has changed? - sp7ObservableCollection<string>to use the control. This will be so. The control itself when interacting with the user can change this collection. And I want the control to react to changes within itself. - iRumba