将依赖属性传递给子视图 [英] Pass dependency property to child view
问题描述
我正在wpf中创建一个用户控件,其中包含用户点击的多个屏幕。
I am currently creating a usercontrol in wpf which consists of several 'screens' that the user will click through.
我正在尝试以相对不错的方式MVVM方式,但是传递属性到每个视图有点麻烦。
I am trying to do this in a relatively nice MVVM way but am having a bit of trouble passing properties to each view.
对于每个屏幕,我已经创建了一个视图,它具有自己的viewmodel(例如View1.xaml, View2.xaml)。主要的用户控件可以访问这些视图:
For each 'screen' I have created a view with it's own viewmodel (e.g. View1.xaml, View2.xaml). The main usercontrol can then access these views:
<UserControl.Resources>
<local:ModuleBaseViewModel x:Key="ViewModelDataSource" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource ViewModelDataSource}}">
<Grid Background="#FF054549">
<local:View1 Visibility="Visible"/>
<local:View2 Visibility="Hidden"/>
</Grid>
</Grid>
现在,我有一些属性,我想在每个视图之间共享(例如背景颜色) 。如果我把这个属性放在主用户控件viewmodel中,那么它被忽略,因为每个视图的DataContext被设置为它自己的viewmodel。
Now, I have some properties that I would like to share between each view (for example background color). If I put this property in the main usercontrol viewmodel then it gets ignored because each view has it's DataContext set to it's own viewmodel.
有没有办法传递属性到每个视图模型,而不必复制它?或者我完全错了吗?
Is there a way of passing down the property to each of the viewmodels without having to duplicate it? Or am I doing it completely wrong?
谢谢!
推荐答案
有一种方法可以解决这个问题。
There are multiple ways you can achive this.
一个解决方案可能是View1,View2等的ViewModels具有包含相同对象并与其绑定的CommonViewModel属性。 / p>
One solution could be that the ViewModels for View1, View2 etc has a CommonViewModel property containing the same object and binding to it.
<Grid Backround={Binding CommonSettings.Background} />
另一种方法是使用相对绑定并绑定到包含视图的研磨的数据文本。 p>
Another way is to use relative binding and bind to the datacontext of the grind containing the views.
<Usercontrol ...>
<Grid Backround={Binding DataContext.Background, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}} />
</UserControl>
这篇关于将依赖属性传递给子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!