简体   繁体   中英

WPF MVVM - How can I pass two variables from the ViewModel associated with the first window to the second ViewModel associated with the second window?

I don't want to use Prism or MVVM Light solutions and would like to pass two parameters to the second window? How could I do that? I was looking for some information on this topic, but unfortunately most of them use packages...

try this:

App.xaml

<Application.Resources>
    <vm:MainViewModel x:Key="YourViewModel" />
</Application.Resources>

MainWindow.xaml

<Window x:Class="ABC.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ABC"
        DataContext="{StaticResource YourViewModel}"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBlock Text="{Binding SomeVar}"/>
    </Grid>
</Window>

SecondWindow.xaml

<Window x:Class="ABC.SecondWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ABC"
        DataContext="{StaticResource YourViewModel}"
        mc:Ignorable="d"
        Title="SecondWindow" Height="450" Width="800">
    <Grid>
        <TextBox Text="{Binding SomeVar}"/>
    </Grid>
</Window>

I guess you could just send parameters in the constructor of the second window, wherever you are creating your window.

var newwin = new SecondWindow("second param is int", 42 );
newwin.Show();

And then just create an another constructor for your window:

public SecondWindow(string a, int b) : this()
{
    var secondVM = (SecondViewModel)DataContext;
    secondVM.IAmSendingYouTwoParams( a,b);
... 
}
        

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