Best practice for dynamically adding controls through copying existent controls in WPF
-
21-09-2019 - |
Question
I have a TabControl
.
While clicking a button I want to add a new TabItem
s to the TabControl
.
Among various techniques I've chosen to create UserControl
inside of a DockPanel
.
Everything works fine, except for the location of control on a new TabItem is not 0 and it is
not expanded on the main form resize.
Everything is quite simple.
<TabItem Header="new control">
<DockPanel LastChildFill="True">
<tc:TabItemTemplate/>
</DockPanel>
</TabItem>
And TabItemTemplate is also located inside a DockPanel, but it's not docked inside a TabItem. What's the catch?
Solution
I would suggest using TabControl.ItemTemplate, and bind TabControl.ItemsSource to ObservableCollection of ViewModels. When user clicks on a button, add new View Model instance to the collection. Refer to this article for more details: WPF Apps With The Model-View-ViewModel Design Pattern