dtc
dtc

Reputation: 10296

How to subscribe to an event in a child usercontrol in Silverlight?

I've got a usercontrol (MyUC) that is programatically added to a page (MainPage) several times.

In MyUC I set the DataContext to a view model like this:

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        DataContext = new MyUCViewModel();
    }

In my view model (MyUCViewModel) I have a collection of data items:

    public MyDataItemCollection MyDataItems { get; private set; }

And in the constructor I have:

    public MyUCViewModel()
    {
        this.MyDataItems = new MyDataItemCollection();
        this.MyDataItems.ChosenItems.CollectionChanged += new NotifyCollectionChangedEventHandler(ChosenItemsChanged);

        this.MyDataItems.Add(new DataItem());
    }

From the above MyDataItems has another collection in it for ChosenItems and I added a NotifyCollectionChangedEventHandler to it.

Other parts of my code add and remove from the ChosenItems collection and that part seems to work ok.

Next I have the event handler method in the view model:

    private void ChosenItemsChanged(object sender, EventArgs e)
    {
        MessageBox.Show("Chosen Items Changed");
    }

This also works and I get a messagebox everytime the user makes a change in the UI that affects the ChosenItems collection.

The part I'm trying to figure out now is how do I set it up so that my MainPage does something when the ChosenItemsChanged event fires in my user controls. What I want to do is have the MainPage loop through the generated MyUC controls on the page and make each usercontrol call a method.

Upvotes: 0

Views: 397

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93611

This is based on the comment as the question was a little misleading:

While not strictly MVVM, as your question appears to be, your should write your User Controls as if it was a third-party control and simply expose a custom event on it. User Controls should always be a black-box with a public interface. For a reusable control that is self-contained (as many are) MVVM is overkill.

e.g.

in your User Control add:

public event EventHandler<MyEventArgs> MyEvent

Create a MyEventArgs class deriving from EventArgs and get it to hold useful parameters (like the selected item).

In your main page add a handler to MyEvent on each User Control you dynamically add.

I actually think the MVVM model is flawed and all this sort of controlling logic and event handlers belong in a Controller class (MVCVM!), but that's another story. :)

Upvotes: 1

Chui Tey
Chui Tey

Reputation: 5574

You can add more event listeners in the MainPage like this:

MyUCViewModel viewModel = myUC.DataContext;
viewModel.MyDataItems.ChosenItems.CollectionChanged 
  += new NotifyCollectionChangedEventHandler(MainPage_ChosenItemsChanged);

Upvotes: 1

Related Questions