我可以将两个不同类型的列表绑定在一起吗?

时间:2014-06-27 10:24:47

标签: c# binding

我对MVVM模式中的绑定有疑问。假设我有三个类MyView,MyViewModel和MyModel。每个包含一个静态列表:

static public List<Line> myViewList;             (for MyView)

static public List<MyViewModel> myViewModelList; (for MyViewModel)

static public List<MyModel> myModelList;         (for MyModel)

是否可以将myViewList与myViewModelList和myViewModelList与myModelList绑定?

1 个答案:

答案 0 :(得分:4)

您是否在询问是否可以将所有三个集合绑定到ItemsControls?

如果是,是的 - 使用CompositeCollection

<ListBox Name="myListBox" Height="300" Width="200" Background="White">
  <ListBox.ItemsSource>
    <CompositeCollection>
      <CollectionContainer
        Collection="{Binding Source={StaticResource GreekGodsData}}" />
      <CollectionContainer
        Collection="{Binding Source={StaticResource GreekHeroesData}}" />
      <ListBoxItem Foreground="Red">Other Listbox Item 1</ListBoxItem>
      <ListBoxItem Foreground="Red">Other Listbox Item 2</ListBoxItem>
    </CompositeCollection>
  </ListBox.ItemsSource>
</ListBox>

MSDN文档中的上述代码。

如果您询问是否可以将三个静态列表绑定到彼此,则不是直接绑定。绑定旨在用于将UI绑定到其后备ViewModel,而不是将多个静态集合绑定到彼此。这可以通过使用类似这样的getter暴露另一个静态集合来实现:

var col1 = new List<long>();
var col2 = new List<string>();

var totalCol = new List<object>();
totalCol.AddRange(col1);
totalCol.AddRange(col2);

请注意,如果您需要收集所有视图,视图模型和模型,则此设计似乎存在根本性的问题。除非你有一些我不明白的情况,这可能是:)