Pass dependency property to child view

2019-09-15 01:43发布

I am currently creating a usercontrol in wpf which consists of several 'screens' that the user will click through.

I am trying to do this in a relatively nice MVVM way but am having a bit of trouble passing properties to each view.

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>

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?

Thanks!

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-15 02:32

There are multiple ways you can achive this.

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} />

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>
查看更多
【Aperson】
3楼-- · 2019-09-15 02:45

Would a better way be to use a ResourceDictionary and reference it in the resources of each view? Then in the resource dictionary I can add a background SolidColorBrush and bind the color to the property?

查看更多
登录 后发表回答