我有一个 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/