Binding two UserControls to the same DataContext,

2020-03-26 05:38发布

问题:

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 DataContext 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:

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.