views:

200

answers:

1

I am working on a UserControl, which is composed of a Chart panel and another area which manipulates some of the chart data i.e. the chart controls (change color of graph, enable or disable stuff on the chart, etc.).

I use a ViewModel to manage the chart and its data, but was thinking maybe it would be nice to make a separate usercontrol out of the chart control area to keep my xaml from getting to big and to separate out the components.

If I do this though, since the controls would need to manipulate the data from the Chart ViewModel, how should I approach it? Can I bind the datacontext of the Chart controls to the data context of the chart, so I just have one viewmodel? Should I give my chart control its own viewmodel and then have the chart panel and chart controls viewmodels talk somehow?

Or just forget about a separate usercontrol and stuff everything into one big viewmodel/xaml control?

What would people recommend in this case?

+1  A: 

You absolutely can have your two UserControls bind to the same ViewModel. You can either bind the DataContext of each to the same object instance, or I suppose you could have the DataContext of one control bound to the datacontext of the other and have it bound to your ViewModel.

If you're starting with a working implementation of your view and your viewmodel, and you feel like the XAML is getting unwieldy, I would agree that you should separate the XAML into multiple views. There's no reason that means you need to separate your ViewModel implementation until you feel that it is becoming incoherent, or just too big. Separating it now would just add complexity as you suggested that they would need to communicate anyway.

You might consider starting by simply creating a UserControl out of the chart controls area and embed that control inside your existing control. Then you don't have to modify any screens that use your chart control.

Mike Schenk
Cool, this will definitely simplify things for me. Can you provide a small example or link that shows me how to bind the DataContext of each to the same object instance, or bind the DataContext of one control to datacontext of the other? Either should work, but I havent found the syntax. Thanks!
Nicros
Figured it out, seems to work okay.In the child UserControl:DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SpectraView}}}"
Nicros
Be careful about relative source data binding. It can be very costly at runtime! Why not bind directly to the other element by it's name?
Matt Casto
I would like to announce that I am an idiot. Thank you. There is no need to bind the DataContext, as if I only create one viewmodel for the whole thing, all children have access to the properties needed.
Nicros