c# - 在 XAML 中的 View 中绑定(bind)多个 ViewModel

标签 c# wpf xaml mvvm windows-phone

我有一个 ViewModel 类“MyViewModel”,里面有一个 ObservableCollection“MyCollection”。

然后在 View 代码隐藏中,我这样做是为了设置数据上下文:

this.DataContext = new MyViewModel();

在 View 的前端
<Pivot ItemsSource="{Binding MyCollection}" SelectionChanged="Pivot_SelectionChanged" Margin="0" Grid.Row="1">

但是如果我需要在这个 View 中使用不同的 ViewModel“MyViewModel2”和“MyCollection2”怎么办。如何跳过此步骤:
this.DataContext = new MyViewModel();

并仅在 xaml 中绑定(bind)?

我试过这个但没有任何结果:
<Pivot ItemsSource="{Binding MyViewModel.MyCollection}" SelectionChanged="Pivot_SelectionChanged" Margin="0" Grid.Row="1">

最佳答案

你最好在同一个 View 模型中使用两个集合......
或者您可以引用两个 subview 模型使用主视图模型类;像这样的东西:

MyViewModel 类:

public class MyViewModel
{
    public ObservableCollection<string> DataInfo { get; set; }

    public MyViewModel()
    {
        DataInfo = new ObservableCollection<string>();            
    }
}

MasterViewModel 类:
public class MasterViewModel
{
    public MyViewModel VM1 { get; set; }
    public MyViewModel VM2 { get; set; }

    public MasterViewModel()
    {
        this.VM1 = new MyViewModel();
        this.VM2 = new MyViewModel();

        VM1.DataInfo.Add("Data 1-1");
        VM1.DataInfo.Add("Data 1-2");

        VM2.DataInfo.Add("Data 2-1");
        VM2.DataInfo.Add("Data 2-2");
    }
}

查看代码隐藏:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MasterViewModel();
    }
}

XAML
<Window x:Class="DeleteMe4SOw.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="400" Width="525">
    <StackPanel Orientation="Vertical">
        <ListView ItemsSource="{Binding VM1.DataInfo}" Height="150" Margin="10" />
        <ListView ItemsSource="{Binding VM2.DataInfo}" Height="150" Margin="10"/>
    </StackPanel>
</Window>

关于c# - 在 XAML 中的 View 中绑定(bind)多个 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26528455/

相关文章:

javascript - 通过 JavaScript 和 JQuery 及其 ID 访问复选框

c# - Mysql 数据适配器 InsertCommand

xaml - UWP:如何创建 "rounded"颜色选择器

xaml - 有没有办法让我的 BackgroundImage 均匀地填充 ContentPage? Xamarin.Forms,XAML

c# - 无法使用 MvxBind 设置 BackgroundColor

c# - 创建一个进程并重定向其输入/输出并且不继承套接字句柄

c# - 强制 INotifyDataErrorInfo 验证

c# - 当属性值更改时更新文本框 - WPF

c# - WPF ComboBox 绑定(bind)未正确更新

wpf - 为什么 WPF 将附加属性用于诸如在网格中定位之类的事情?