簡體   English   中英

WPF MVVM - 如何將兩個變量從與第一個 window 關聯的 ViewModel 傳遞到與第二個 window 關聯的第二個 ViewModel?

[英]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?

我不想使用 Prism 或 MVVM Light 解決方案,想將兩個參數傳遞給第二個 window? 我怎么能那樣做? 我一直在尋找有關此主題的一些信息,但不幸的是,其中大多數都使用包...

嘗試這個:

App.xaml

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

主窗口.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>

我想你可以在第二個 window 的構造函數中發送參數,無論你在哪里創建 window。

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

然后為您的 window 創建另一個構造函數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM