【问题标题】:Howto bind Views to Viewmodel in a MVVM-Environment with XAML and WPF in C#如何在 C# 中使用 XAML 和 WPF 在 MVVM 环境中将 View 绑定到 Viewmodel
【发布时间】:2012-05-02 20:40:22
【问题描述】:

如果我想将视图绑定到视图模型,我将以下内容添加到我的 XAML 代码的资源中:

<Window.Resources>
    <DataTemplate DataType="{x:Type MyViewModel}" >
        <views:MyView />
    </DataTemplate>
</Window.Resources> 

是否有可能在 C#-Code 中将 (viewmodel,view)-resource-entry 添加到我的资源字典中?

以下两行创建密钥并将其添加到字典中:

DataTemplateKey key = new DataTemplateKey(typeof(MyViewModel));
View.WindowName.Resources.Add(key, value);

但是如何从必须具有 System.Windows.Baml2006.KeyRecord 类型的 MyView 创建值?

【问题讨论】:

    标签: c# wpf xaml mvvm


    【解决方案1】:

    here 是一个关于如何使用 c# 代码创建数据模板的示例。

    ps:您的问题标题应该类似于如何使用 c# 代码创建数据模板。顺便说一句,这与 mvvm 无关。更何况这段代码当然不应该进入视图模型;)

    编辑:

    DataTemplate temp = new DataTemplate();
    temp.DataType = typeof (MyViewModel);
    
    FrameworkElementFactory fac = new FrameworkElementFactory(typeof(MyView));
    
    temp.VisualTree = fac;
    
    View.WindowName.Resources.Add(new DataTemplateKey(typeof(MyViewModel)), temp );
    

    在 xaml 中更容易:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 2019-05-29
      • 1970-01-01
      • 2011-01-21
      • 2011-02-08
      • 2013-08-29
      相关资源
      最近更新 更多