简体   繁体   English

MVVM视图模型参考视图

[英]MVVM viewmodel reference view

I am required to use the mvvm pattern. 我需要使用mvvm模式。 I know that the viewmodel should not care about the view from what I been reading. 我知道viewmodel不应该在乎我一直在阅读的视图。 As a result I don't know how to solve this problem: 结果,我不知道如何解决这个问题:

I have a dll that basically turns a textbox and listview into an autocomplete control: 我有一个dll,基本上可以将文本框和listview变成自动完成控件:

SomeDll.InitAutocomplete<string>(TextBox1, ListView1, SomeObservableCollection);

anyways I don't know how to call that method from the viewmodel using the mvvm patter. 无论如何,我不知道如何使用mvvm模式从viewmodel调用该方法。 if I reference the controls in the view I will be braking the rules. 如果我在视图中引用控件,则将停止规则。

I am new to MVVM pattern and my company requires me to follow it. 我是MVVM模式的新手,我的公司要求我遵循它。 what will be the most appropriate way of solving this problem? 解决这个问题的最合适方法是什么?

I know I will be able to solve it by passing the entire view to the viewmodel as a constructor parameter but that will totaly break the mvvm pattern just because I need to reference two controls in the view. 我知道我可以通过将整个视图作为构造函数参数传递给viewmodel来解决它,但这将完全破坏mvvm模式,因为我需要在视图中引用两个控件。

What you're doing here is a pure view concern, so I'd recommend doing it in the view (ie the code-behind). 您在这里所做的只是纯粹的视图方面的考虑,因此我建议在视图中进行(即,隐藏代码)。 The view knows about the VM and its observable collection, so why not let the code behind make this call? 该视图了解VM及其可观察的集合,那么为什么不让背后的代码进行此调用呢?

(I'd also recommend seeing if you can get a non-code/XAML API for "SomeDll", but I have no idea how much control you might have over that) (我也建议您查看是否可以为“ SomeDll”获得非代码/ XAML API,但我不知道您可能对此有多少控制权)

There are two things that I'd point out here - 我在这里指出两件事-

First, this is effectively all View-layer code. 首先,这实际上是所有View层代码。 As such, using code behind isn't necessarily a violation of MVVM - you're not bridging that View->ViewModel layer by including some code in the code behind, if necessary. 因此,在后面使用代码不一定违反MVVM-如果需要,您不会在后面的代码中包含一些代码来桥接View-> ViewModel层。

That being said, this is often handled more elegantly in one of two ways - 话虽这么说,但通常可以通过以下两种方式之一更优雅地处理它:

  1. You could wrap this functionality into a new control - effectively an AutoCompleteTextBox control. 您可以将此功能包装到新控件中-有效地是AutoCompleteTextBox控件。 This would allow you to include the "textbox" and "listview" visual elements into the control template, and bind to the completion items within Xaml. 这将允许您将“文本框”和“列表视图”可视元素包括到控件模板中,并绑定到Xaml中的完成项。

  2. You could turn this into an attached property (or Blend behavior), which would allow you to "attach" it to a text box, and add that functionality (all within xaml). 您可以将其转换为附加属性(或Blend行为),使您可以将其“附加”到文本框中,并添加该功能(全部在xaml中)。 The items collection would then become a binding on the attached property (or behavior). 然后,items集合将成为附加属性(或行为)的绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM