Binding ObservableCollection items to UserControl in WrapPanel?

99封情书 提交于 2019-12-01 00:06:24

问题


I may just be missing something obvious here, so I apologize if this is a really dumb question. I have a WrapPanel in a view that I need to bind to an ObservableCollection on the ViewModel. This ObservableCollection contains a different type of ViewModel that needs to be bound to another type of view when displayed in the WrapPanel. The goal is to create a wrappable list of items, each of which displays via an instance of a smaller view which should be added to the WrapPanel.

I am using MVVM, and the ViewModel does not have direct access to the View. I would rather not create a binding between the ViewModel and the View if at all possible, so manually adding items to the WrapPanel.Children collection is not a viable option. I am at a loss as to how I can bind a collection of child ViewModel objects to the WrapPanel in such a way that it will create instances of another view and add them to itself. Am I simply approaching the problem incorrectly? I figure there is probably a DataTemplate involved, but it doesn't appear that a WrapPanel has a DataTemplate, nor is it bindable.

Thanks for any insight.


回答1:


What you need is a ListView that uses a WrapPanel to host all of the items.

<ListView ItemsSource={...}>
   <ListView.ItemsPanel>
     <ItemsPanelTemplate>
       <WrapPanel IsItemsHost="True" />
     </ItemsPanelTemplate>
   </ListView.ItemsPanel>
   <ListView.ItemTemplate>
      <DataTemplate>
        <!-- Fill in how you want each item to look here -->
      </DataTemplate>
   </ListView.ItemTemplate>
</ListView>



回答2:


Use an ItemsControl, and set its ItemsPanel to a WrapPanel:

<ItemsControl ItemsSource="{Binding Something}" ItemTemplate="{StaticResource YourDataTemplate}">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <WrapPanel />
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>


来源:https://stackoverflow.com/questions/1575976/binding-observablecollection-items-to-usercontrol-in-wrappanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!