Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

registering an ObservableCollection as a readonly dependency property

$
0
0

Hi group,
let's say I've the followed scenario: a simple UserControl internally uses an ObservableCollection<string> object and it should expose it as a readonly dependency property. I'd then like to observe the collection changes during the control lifetime, i.e. handle the CollectionChanged event fired by that object.

I've tried to register a readonly DP as follows:

 

private static readonly DependencyPropertyKey SelectedValuesKey =
 DependencyProperty.RegisterReadOnly("SelectedValues",
 typeof(ObservableCollection<string>), typeof(TheDummyControl),
  new PropertyMetadata());

public static readonly DependencyProperty SelectedValuesProperty =
 SelectedValuesKey.DependencyProperty;

 

but I get an exception during control construction. If instead I register a DP as "usual" with Register, like:

 

public static readonly DependencyProperty SelectedValuesProperty =
    DependencyProperty.Register("SelectedValues", typeof(ObservableCollection<string>), typeof(TheDummyControl),
    new FrameworkPropertyMetadata(new ObservableCollection<string>(), null));

 

the control constructs and shows OK but (apart from the fact that I'd need a readonly DP, as I do not want client code to replace my collection, but just to use it to add/remove items) I cannot manage to handle CollectionChanged: if I add something like:

SelectedValues.CollectionChanged += handler...

the code compiles but my handler for CollectionChanged is never called.

There must be obviously something wrong... could anyone give a hint?


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>