我正在构建一个复杂的 UI 应用程序,其中一个窗口包含一个控件,它是一个 Canvas ,它绘制节点的有向无环图 (DAG)。因为那个窗口相当复杂(而且因为我一开始对 WPF 一无所知),所以我想我会使用 CustomControl(而不是用户控件,因为我认为用户控件用于将事物组合在一起)。我正在尝试构建的应用程序应该遵循 MVVM。
现在我正在创建 GraphControl
作为 Selector
的子类控制。
问题 #1:该类是 ViewModel 吗?我不明白 GraphControl
的作用伟大的 MVVM 故事中的类。
问题 #2:当我将它添加到我的主应用程序时,我必须执行以下操作:
<GraphControl DataContext="{Binding RelativeSource={RelativeSource Self}}" ...
在我看来,我真的不明白这些东西应该如何工作。
帮助?
编辑:显然那个人和我有同样的问题(https://mutelight.org/datacontext-in-a-custom-control)。文章中给出的解决方案是这样做的:
<GraphControl><Grid DataContext="{Binding RelativeSource={RelativeSource Self}}" ...
不过,这对我来说听起来很骇人听闻……
最佳答案
Question #1: Is that class the ViewModel? I don't understand the role of the GraphControl class in the grand MVVM story.
没有。
GraphControl
只是属于 View 的另一个控件。内置控件的示例包括 TextBox
, Button
和 ListBox
在其他几个中。您的 GraphControl
只是另一种类型的控制。View 模型是控件绑定(bind)的对象。有关 MVVM 设计模式和每个组件的角色的基本介绍,请参阅 MSDN:https://msdn.microsoft.com/en-us/library/hh848246.aspx .
Question #2: When I add it to my main application, I have to do something like:
您可以设置
DataContext
以一种或另一种方式控制。最常见的方法是设置 DataContext
父窗口到 View 模型的实例,例如:public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
子元素继承
DataContext
除非 DataContext
属性显式设置为其他内容。这意味着您的控件将继承
DataContext
其父面板将继承 DataContext
从它的父元素等等。以下设置
DataContext
控制到自身,这意味着您可以绑定(bind)到 GraphControl
的任何属性没有指定明确来源的类:<GraphControl DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>
是否要这样做取决于您的要求。
关于c# - MVVM 中的自定义控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42692593/