MVVM Light中如何从继承DataContext的面板绑定ViewModel属性
适配MVVM Light的绑定解决方案
针对你遇到的问题,这里有三种简洁且适配ViewModel Locator模式的解决办法:
方法一:通过RelativeSource向上定位父级UserControl的上下文
直接在绑定里用RelativeSource找到外层的UserControl,它的DataContext就是你的ViewModel:
<TextBlock Text="{Binding Path=DataContext.ApplicationVersion, RelativeSource={RelativeSource AncestorType=UserControl}}" />
这种方式不需要额外配置,直接复用视图已有的ViewModel关联。
方法二:给UserControl命名后用ElementName绑定
先给你的UserControl添加名称(比如x:Name="RootControl"),再通过ElementName绑定到它的DataContext:
<UserControl x:Name="RootControl" ...> <!-- 原有视图结构 --> <TextBlock Text="{Binding Path=DataContext.ApplicationVersion, ElementName=RootControl}" /> </UserControl>
逻辑直观,适合视图层级不复杂的场景。
方法三:直接绑定ViewModel Locator的对应属性
既然你的视图已经通过Locator静态资源获取ViewModel,也可以直接绑定到Locator的SettingUserEdit属性下的ApplicationVersion:
<TextBlock Text="{Binding Path=SettingUserEdit.ApplicationVersion, Source={StaticResource Locator}}" />
这个方案完全贴合你项目已有的Locator模式,无需调整视图结构。
原理说明
你的EditUserContainer把DataContext设为SelectedUser后,内部控件默认绑定的是用户对象,但ViewModel本身存在于父级UserControl的DataContext中,或者可以通过Locator直接访问。以上方法都是绕开当前StackPanel的DataContext,直接指向ViewModel上下文,既保留了原有用户字段绑定的简洁性,又能获取ViewModel的其他属性。
内容的提问来源于stack exchange,提问作者Göran Roseen
相关产品推荐
相关产品推荐

