C# 如何在MainWindow.xaml中绑定多个ViewModels?
我的wpf Mvvm项目中有一个MainViewModel和一个OtherViewModel。 在MainWindow.Xaml中,我将MainViewModel设置为网格的DataContext。但是,我想将OTerViewModel设置为TextBox控件的DataContext,它位于网格中。我如何实现它?xaml代码作为休耕C# 如何在MainWindow.xaml中绑定多个ViewModels?,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我的wpf Mvvm项目中有一个MainViewModel和一个OtherViewModel。 在MainWindow.Xaml中,我将MainViewModel设置为网格的DataContext。但是,我想将OTerViewModel设置为TextBox控件的DataContext,它位于网格中。我如何实现它?xaml代码作为休耕 <Window.Resources> <viewModels:MainWindowViewModel x:Key="Windows1Vie
<Window.Resources>
<viewModels:MainWindowViewModel x:Key="Windows1ViewModel" />
</Window.Resources>
<Grid DataContext="{StaticResource Windows1ViewModel}">
.....
<TextBox "require to bind OtherVeiwModel here"/>
.....
</Grid>
.....
.....
XAML:
<TextBox DataContext="{Binding OtherViewModel, Mode=OneWay}" "require to bind OtherVeiwModel here"/>
我是否必须在某处实例化OtherViewModel?如果我在MainWindowViewModel中将OtherViewModel实例化为otherVM
,我可以使用Window1ViewModel.otherVM
作为文本框的DataContext吗?我不确定,我想您可以尝试DataContext=“{Binding Source={StaticResource Window1ViewModel},Path=OtherViewModel}”
public class MainViewModel
{
public OtherViewModel OtherViewModel{get {retrurn new OtherViewModel();}}
}
<TextBox DataContext="{Binding OtherViewModel, Mode=OneWay}" "require to bind OtherVeiwModel here"/>