Home > Enterprise >  WPF MVVM - How can I pass two variables from the ViewModel associated with the first window to the s
WPF MVVM - How can I pass two variables from the ViewModel associated with the first window to the s

Time:08-18

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...

CodePudding user response:

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>

CodePudding user response:

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);
... 
}
        
  • Related