简体   繁体   中英

How can i share same ViewModel between two views in WPF?

I have this view:

<Window x:Class="Ohmio.Client.PruebasView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Ohmio.Client"   
    Title="Pruebas" Height="284" Width="626">
<Window.DataContext>
    <local:PruebasViewModel/>
</Window.DataContext>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40"/>
        <RowDefinition Height="40"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Label Content="Create View"/>
    <Button Grid.Row="1" Content="Create child View" Click="Button_Click_1"></Button>
    <ContentPresenter x:Name="ContentPrt" Grid.Row="2" Margin="5"></ContentPresenter>        
</Grid>

My idea is to load a second view(child view) in the content presenter. Just for testing i'm doing this from code-behind:

this.ContentPrt.Content = new ModalViewModel();

So my question is: How can I make the new view(the one load on contentPresenter) share the same dataContext with PruebasView? (In this case, PruebasViewModel)

Thanks!

If I understood your question correctly, it's simple. Just pass PruebasViewModel to ContentPresenter as the data context.

<ContentPresenter x:Name="ContentPrt" DataContext={Binding} Grid.Row="2" Margin="5"></ContentPresenter>

I suppose that ModalViewModel is your child view class. So when you add it to the content presenter, your View becomes a part of your Visual Tree, so it automatically shares the DataContext of the main window.

Pratically WPF makes of the job for you: the content presenter's content will "see" the PruebasViewModel by its own.

EDIT

I did not read that you are using Caliburn Micro, but the idea does not change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM