c# - 如何在 MainWindow.xaml 中绑定(bind)多个 ViewModel?

标签 c# wpf xaml mvvm

我的 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/

相关文章:

c# - 接口(interface)作为一个用于继承的原因,而不是实现者

c# - MapPath 与 VirtualPathUtility.ToAbsolute

c# - 使用 MVVM 模式从 View 模型到 WPF 中的 View 的条件绑定(bind)

c# - 使用 Kinect 为简单的静态手势创建手势定义

c# - 真正的模态窗口可能吗?

c# - 如何处理 C# 类中的所有异常,其中 ctor 和终结器都抛出异常?

c# - 停止覆盖矩形接收 wpf 点击事件

xaml - 在Xamarin表单TabBar中使用图标字体

xaml - 为 ContentDialog 配置覆盖背景颜色

c# - 将整数转换为对象并返回会导致 InvalidCastException