How to bind items of a TabControl to an observable collection in wpf?

橙三吉。 提交于 2019-11-27 01:47:14

问题


What is the simplest example of binding the items of a TabControl to an ObservableCollection?

Each tab's content will have unique data, and indeed this data will have observableCollections of its own bound to the items components.

Currently I have a user control, which I would like to set as the content of each tab as soon as it is created. I also need to dynamically set the datacontext of this new user control when the tab is created. So, essentially, I would like the tabcontrol's observablecollection contain modelviews that map to the data in each tab.

On top of that, I need to do all this without violating MVVM in WPF! Any help?

Much appreciated!


回答1:


Basic example :

<Window.Resources>

    <DataTemplate x:Key="templateForTheContent" DataType="{x:Type vm:TheViewModelType}">
        <v:YourUserControl/>
    </DataTemplate>

    <DataTemplate x:Key="templateForTheHeader" DataType="{x:Type vm:TheViewModelType}">
        <TextBlock Text="{Binding ThePropertyToDisplayInTheHeader}"/>
    </DataTemplate>

</Window.Resources>

...

<TabControl ItemsSource="{Binding YourCollection}"
            ContentTemplate="{StaticResource templateForTheContent}"
            ItemTemplate="{StaticResource templateForTheHeader}">
</TabControl>


来源:https://stackoverflow.com/questions/1261118/how-to-bind-items-of-a-tabcontrol-to-an-observable-collection-in-wpf

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