For inject multiple ViewModels into a single View, the way to do it might be by encapsulating them in a third view model. Let's call that CombinedViewModel. The CombinedViewModel would have MainWindowViewModel and AnotherViewModel as public properties, that way you could use both for binding. Such as the following example。
View:
<Window.Resources>
<local:MainViewModel x:Key="mvm"/>
</Window.Resources>
<Grid DataContext="{StaticResource mvm}" >
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid x:Name="grid1" Background="AliceBlue" Height="100" DataContext="{Binding VM1}" >
<TextBlock VerticalAlignment="Top" Foreground="Black" Background="White" HorizontalAlignment="Left" Text="{Binding String1}" Width="100" Height="40">
<TextBlock.ToolTip>
<TextBlock>
<Run Text="{Binding Source={x:Reference tb}, Path=Text}" FontWeight="Bold"/>
</TextBlock>
</TextBlock.ToolTip>
</TextBlock>
<TextBlock Background="White" Foreground="Black" Width="100" Height="40" Text="{Binding ElementName=tb,Path=DataContext.String2}"/>
</Grid>
<Grid x:Name="grid2" Grid.Row="1" Background="LightGreen" Height="100" DataContext="{Binding VM2}">
<TextBlock x:Name="tb" VerticalAlignment="Top" Foreground="Black" Background="White" HorizontalAlignment="Left" Text="{Binding String2}" Width="100" Height="40"/>
</Grid>
</Grid>
ViewModel:
public class MainViewModel
{
public ViewModel1 VM1 { get; set; }
public ViewModel2 VM2 { get; set; }
public MainViewModel()
{
VM1 = new ViewModel1();
VM2 = new ViewModel2();
}
}
public class ViewModel1
{
public string String1 { get; set; } = "string1";
}
public class ViewModel2
{
public string String2 { get; set; } = "string2";
}
The result:
-
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.