0

Suppose there's a UserControl with a dependency property (a collection of some object) - is there anyway for, when the dependency property is set, to automatically execute a command exposed by the view-model without breaking encapsulation and doing this the "MVVM way"?

And yes I know I can always wire-up the property changed static handler, cast the object to an instance of my user control, grab the data-context, cast that to the view-model and call the command manually

EDIT: maybe an example would help. My UserControl has a "ItemsSource" dependency property ..I want it to be settable to a collection of ObjectA. I have an "Items" dependency property which is only gettable and is a collection of ObjectB.

I want behavior such that if I set ItemSource, my collection of ObjectAs will be transformed one-to-one by the view-model into ObjectBs, and the Items dependency property will automatically reflect this.

To do this I want a write-only ItemsSource and a read-only Items property.

blue18hutthutt
  • 3,191
  • 5
  • 34
  • 57

2 Answers2

1

Just to make it clear:

  • You want a write-only DependencyProperty ItemsSource on the Control
  • You want a read-only Dependency-Property Items on the control's ViewModel
  • Items should return a transformed version and reflect changes of ItemsSource

If that is what you want, would that be a solution:

  • Add an ItemsSource-Property to the ViewModel which is the same type as in the control
  • Two-way-bind it to the control's DP
  • In the Set-accessor of the ItemsSource property of the ViewModel, fill the Items collection with transformed versions of the ItemsSource elements
  • Fire OnPropertyChanged for the Items property

ItemsSource of the Control and ViewModel is readable in this scenario. Write-only DPs are not possible as far as I know:

SO Thread about write-only DPs

However, this approach should work anyway.

Hope this helps, cheers...

Community
  • 1
  • 1
Marc
  • 12,706
  • 7
  • 61
  • 97
0

If you use ObservableCollection you can use it's CollectionChanged event.

ViewModel:

  private ObservableCollection<object> _Objects
  public ObservableCollection<object> Objects
  {
    get { return _Objects; }
    set { _Objects = value; 
           OnPropertyChanged(new PropertyChangedEventArgs("Objects"));
     }
  }

  Objects.CollectionChanged+= new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Objects_CollectionChanged); 

 void Objects_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {

    }
mahboub_mo
  • 2,908
  • 6
  • 32
  • 72