【问题标题】:How to access the viewmodel of a dynamically added UserControl如何访问动态添加的 UserControl 的视图模型
【发布时间】:2020-09-17 10:00:14
【问题描述】:

场景是这样的, 我有一个 MainWindow.xaml,作为此窗口的一部分,我将加载一个 UserControl。 这个 UserControl 实际上是在其他项目中,它被添加到 ResourceDictionary 中,键如下,

<ContentControl x:Key="Template1">
    <customcontrol:Template1UserControl/>
</ContentControl>

所以在MainWindow.xaml中,我将这个键引用如下,

<ContentControl Content="{StaticResource Template1}"/>

现在,像这样我可以在 MainWindow.xaml 中看到 Template1UserControl,但问题是我不知道如何访问 的数据上下文MainWindow.xaml中的>Template1UserControl

Template1 就像一个变量,明天可以有Template2UserControl,可以是任何东西。

谁能帮我在 WPF 中做到这一点。 如果我应该在这里应用一些其他策略来访问 Template1UserControl 的视图模型,那也是非常受欢迎的。

提前致谢!

【问题讨论】:

  • 一个包裹在 ContentControl 中的 UserControl,又包裹在另一个 ContentControl 中?看起来很奇怪。 UserControl 应改为在 DataTemplate 中声明。您可以将视图模型类型的实例分配给 ContentControl 的 Content 属性,并且会自动选择适当的 DataTemplate(具有与视图模型类型匹配的 DataType)。为了使这项工作,UserControl 不能设置自己的 DataContext,即具有私有视图模型。
  • 您想要访问什么?顺便说一句,用法看起来像您正在制作 custom 控件,那些不需要视图模型,而是一组依赖属性。如果某些东西将被数据模板化,那么 ViewModel (MVVM) 是有意义的,这是另一种方式:您宁愿手头有一个视图模型实例。

标签: c# .net wpf xaml


【解决方案1】:

MainWindow 中的ContentControl 一个x:Name

<ContentControl x:Name="cc" Content="{StaticResource Template1}"/>

...并尝试转换属性:

var theTemplate = cc.Content as ContentControl;
var theUserControl = theTemplate?.Content as UserControl;
var theDataContext = theUserControl?.DataContext;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 2013-05-29
    相关资源
    最近更新 更多