CREATING VIEWMODEL TO VIEW MAPPINGS

本文介绍了一种在WPF应用程序中使用数据模板创建视图和视图模型对的方法。通过这种方式可以方便地将ViewModel实例渲染为对应的View,特别是在无法直接添加静态XAML资源的情况下提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


One of my favorite approaches to creating View/ViewModel pairs in WPF it to use data templates. Say you have a ViewModel called MyViewModel and it should be displayed in the UI as the View MyView.

We can create a fairly straightforward DataTemplate defined as:

<DataTemplate DataType="{x:Type local:MyViewModel}">
  <local:MyView />
</DataTemplate>

Whenever we add the ViewModel instance into a Window or a ContentControl, it will render using the DataTemplate, which just happens to be the View.

If we ever run into a dynamic scenario in which we are unable to easily add static XAML as a resource dictionary into an existing resource dictionary, as we might in a Prism module scenario, we can use the following method instead. Just declare it in our MainWindow or Application and expose it through an interface inside that can be accessed through a service container.

  1. public void RegisterViewModelToViewMapping<tviewmodel, tview="">()  
  2. {  
  3.     DataTemplate template = new DataTemplate(typeof(TViewModel));  
  4.     template.VisualTree = new FrameworkElementFactory(typeof(TView));  
  5.   
  6.     DataTemplateKey key = new DataTemplateKey(typeof(TViewModel));  
  7.     Resources.Add(key, template);  
  8. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值