问题描述
我正在开发一个 UserControl
,它由一个 Chart
面板组成,另一个区域用于操作一些图表数据,即图表控件(更改图表颜色,启用或禁用图表上的内容等)。
我使用 ViewModel
来管理图表及其数据,但是也许认为将图表控件区域中的单独的用户控件放在一起是很好的,以保持我的xaml不会变大并分离出组件。 / p>
如果我这样做,因为控件将需要从 Chart
ViewModel
,我该怎么办?我可以将 Chart
控件的 DataContext
绑定到 DataContext
Chart
,所以我只有一个 ViewModel
?我应该给我的图表控件自己的viewmodel,然后让图表面板和图表控件viewmodels说话吗?
或者只是忘记一个单独的用户控件,并将所有东西都放到一个大viewmodel / xaml控件?
在这种情况下,人们会推荐什么?
您绝对可以将两个 UserControl
绑定到相同的 ViewModel
。您可以将每个 DataContext
绑定到同一对象实例,或者我想您可以将$ code> DataContext 控制绑定到其他的 DataContext
,并将其绑定到您的 ViewModel
。
如果您开始执行视图和viewmodel,并且您觉得XAML变得笨重,我会同意将XAML分成多个视图。没有理由意味着你需要分开你的 ViewModel
实现,直到你觉得它变得不连贯,或者太大了。分开它现在只会增加复杂性,因为您建议他们需要沟通。
您可以考虑从简单地创建一个 UserControl
出图表控件区域,并将该控件嵌入到现有控件中。然后,您不必修改任何使用图表控件的屏幕。
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?
You absolutely can have your two UserControl
s 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.
这篇关于将两个UserControl绑定到同一个DataContext或ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!