WPF的DataContext问题 [英] WPF's DataContext questions
问题描述
我问了它如何与INotifyPropertyChanged接口一起工作( WPF如何实现INotifyPropertyChanged? a>),这需要我将XAML的DataContext连接到INotifyPropertyChanged继承实例,如下所示。
I asked about how does it work with INotifyPropertyChanged interface( How does WPF INotifyPropertyChanged work? ), and it requires me to connect XAML's DataContext to the INotifyPropertyChanged inherit instances as follows.
MainViewModel model = new MainViewModel();
this.DataContext = model;
我还发现了一个建议,要求对每个XMAL使用的DataContext进行注释( http://joshsmithonwpf.wordpress.com/2009/10/24/xaml -tip-datacontext-comment / )。
And I also found a recommendation to have a comment for DataContext that each XMAL uses( http://joshsmithonwpf.wordpress.com/2009/10/24/xaml-tip-datacontext-comment/ ).
当我有多个XAML文件时,并且想将DataContext链接到其他ViewModel时,我想需要使每个XAML.CS文件包含此代码(每个xaml.cs的模型都不同): this.DataContext = model;
。
When I have multiple XAML files, and when I want to link the DataContext to different ViewModel, I guess I need to make the each XAML.CS file to contain this code (model varies for each xaml.cs) :this.DataContext = model;
.
- 这正确吗?
- 如何在XAML文件中执行相同的操作?
- 这种DataContext背后的魔力是什么?我的意思是,DataContext如何工作?
推荐答案
-
据我所知是正确的,因为这是重复性很强的操作,某些MVVM框架会为您进行此链接。
Yes that is correct as far as i know, since this is quite repetetive some MVVM frameworks do this linking for you.
在XAML中:
<UserControl ... xmlns:vm="clr-namespace:MyApp.ViewModels"> <UserControl.DataContext> <vm:MyViewModel /> </UserControl.DataContext> <!-- ... --> </UserControl>
-
它在路径相对于DataContext的地方启用短绑定,例如
{绑定名称}
绑定到DataContext.Name
。请阅读数据绑定概述(如果尚未安装)。
Please read the Data Binding Overview if you haven't.
这篇关于WPF的DataContext问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!