将两个 UserControl 绑定到同一个 DataContext 或 ViewModel? [英] Binding two UserControls to the same DataContext, or ViewModel?

查看:30
本文介绍了将两个 UserControl 绑定到同一个 DataContext 或 ViewModel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 UserControl,它由一个 Chart 面板和另一个操作图表数据的区域组成,即图表控件(更改图表颜色,启用或禁用图表上的东西等).

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.).

我使用 ViewModel 来管理图表及其数据,但我想在图表控制区域之外创建一个单独的用户控件以防止我的 xaml 变得庞大和分离出组件.

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.

如果我这样做,由于控件需要操作 Chart ViewModel 中的数据,我应该如何处理它?能不能把Chart控件的DataContext绑定到ChartDataContext,这样我就只有一个<代码>视图模型?我应该给我的图表控件自己的视图模型,然后让图表面板和图表控件的视图模型以某种方式说话吗?

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?

或者只是忘记一个单独的用户控件并将所有内容都放入一个大的 viewmodel/xaml 控件中?

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

在这种情况下人们会推荐什么?

What would people recommend in this case?

推荐答案

你绝对可以让你的两个 UserControl 绑定到同一个 ViewModel.您可以将每个控件的 DataContext 绑定到同一个对象实例,或者我想您可以将一个控件的 DataContext 绑定到 DataContext另一个并将其绑定到您的 ViewModel.

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.

如果您从视图和视图模型的工作实现开始,并且您觉得 XAML 变得笨拙,我同意您应该将 XAML 分成多个视图.没有理由意味着您需要分离您的 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.

您可以考虑首先从图表控件区域创建一个 UserControl 并将该控件嵌入到现有控件中.这样您就不必修改任何使用图表控件的屏幕.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆