我的 wpf Mvvm 项目中有一个 MainViewModel 和一个 OtherViewModel。
在 MainWindow.Xaml 中,我将 MainViewModel 设置为 Grid 的 DataContext。但是,我想将 OhterViewModel 设置为 TextBox 控件的 DataContext,它位于 Grid 中。我该如何实现? xaml 代码作为休闲方式。
<Window.Resources>
<viewModels:MainWindowViewModel x:Key="Windows1ViewModel" />
</Window.Resources>
<Grid DataContext="{StaticResource Windows1ViewModel}">
.....
<TextBox "require to bind OtherVeiwModel here"/>
.....
</Grid>
最佳答案
<Window.Resources>
<viewModels:MainWindowViewModel x:Key="Windows1ViewModel" />
<viewModels:OtherViewModel x:Key="OtherViewModel" />
</Window.Resources>
<Grid DataContext="{StaticResource Windows1ViewModel}">
<TextBox DataContext="{StaticResource OtherViewModel}" "require to bind OtherVeiwModel here"/>
</Grid>
或者,您的 MainViewModel 可能会保留对您的 OtherViewModel 的引用,您可以将 TextBox 的 DataContext 绑定(bind)到该备用 View 模型。
CS:
public class MainViewModel
{
public OtherViewModel OtherViewModel{get {retrurn new OtherViewModel();}}
}
XAML:
<TextBox DataContext="{Binding OtherViewModel, Mode=OneWay}" "require to bind OtherVeiwModel here"/>
关于c# - 如何在 MainWindow.xaml 中绑定(bind)多个 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18684530/