在XAML的视图中绑定多个ViewModel

本文关键字:ViewModel 绑定 XAML 视图 | 更新日期: 2023-09-27 18:27:38

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

然后在后面的视图代码中,我这样做是为了设置数据上下文:

this.DataContext = new MyViewModel();

并且在视图的前端

<Pivot ItemsSource="{Binding MyCollection}" SelectionChanged="Pivot_SelectionChanged" Margin="0" Grid.Row="1">

但是,如果我需要在该视图中使用不同的ViewModel"MyViewModel2"answers"MyCollection2",该怎么办。如何跳过此步骤:

this.DataContext = new MyViewModel();

并且仅在xaml中结合?

我试过了,但没有任何结果:

<Pivot ItemsSource="{Binding MyViewModel.MyCollection}" SelectionChanged="Pivot_SelectionChanged" Margin="0" Grid.Row="1">

在XAML的视图中绑定多个ViewModel

您最好在同一视图模型中使用两个集合。。。或者,您可以使用一个主ViewModel类来引用两个子ViewModel;像这样的东西:

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>

这是我的主类:

class CompositeViewModel
{
    public TripsResponseTypeViewModel tripsResponseTypeViewModel { get; set; }
    public TripsViewModel tripsViewModel { get; set; }
}

在TripsResponseTypeViewModel中我有:

...
    private ObservableCollection<TripsResponseType> _tripsViewModelDataSource;
    public ObservableCollection<TripsResponseType> TripsViewModelDataSource
    {
        get
        {
            if (null == this._tripsViewModelDataSource)
            {
                this._tripsViewModelDataSource = new ObservableCollection<TripsResponseType>();
            }
            return this._tripsViewModelDataSource;
        }
    }
...

在我的视图中,我想将此TripsViewModelDataSource设置为数据透视的ItemsSource,如下所示:

<Pivot ItemsSource="{Binding tripsResponseTypeViewModel.TripsViewModelDataSource}"...

在View.xaml.cs中,我按照你说的做了:

this.DataContext = new CompositeViewModel();

什么都没有。。