views:

41

answers:

1

I have a UserControl which contains 4 ToggleButtons and I'd like to trigger a custom event that an interested object can listen for which provides a status, based on the ToggleButton Checked values and also value(s) from the DataContext object.

Getting the ToggleButton checked values and deriving a status is simple enough, however I can't work out how I access the DataContext object within the C# codebehind.

For example, if an interested object receives the RoutedEvent from the UserControl, I would like it to be able to access values from the UserControl's DataContext object.

Will I need to expose specific properties from the DataContext object or can I somehow expose the DataContext object from the UserControl's API?

Update.

To explain the problem a little more, I have a list of items which creates a set of UserControl instances in a container, I attach event listeners to each item as it's added to the container and send an event from one of the UserControls when it's child controls are clicked / checked etc.

Getting a reference to the UserControl that dispatched the event is straightforward enough, but I can't access the DataContext object, do I need to assign a public property to expose the DataContext object ...

e.g.

private ControlViewModel myControlViewModel;
public ControlViewModel MyControlViewModel {
    get { return myControlViewModel; }
    set 
    {   
        this.DataContext = value;
        myControlViewModel = value;
    }
}

or is there a better way?

Any tips would be appreciated, Thank you.

A: 

Well, it looks like I should've tried the simplest solution first...

...of course I can access the DataContext object like this:

(userControl.DataContext as ControlViewModel).requiredProperty;

Update

So I ended up passing the DataContext view model reference via a event/delegate pair like this...

public delegate void StatusChangedHandler(string status, UserControlViewModel model);

public event StatusChangedHandler StatusChanged;

And then just invoked the event like this...

StatusChanged.Invoke("message", DataContext as UserControlViewModel) 
// or DataContext as IUserControlModelInterface

Which allowed me to adequately aggregate events from the UserContol's child controls, and access the DataContext model from an event handler.

I still wonder if there is a more best practice way to do this?

slomojo