Using TabControl to display tabbed panels with varying content #17537
-
I am new to Avalonia, having trouble to write a simple application that displays 3 tabbed panels in its MainView. I defined the TabControl in MainView as you can see below:
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 8 replies
-
I think that the TabControl ItemsSource should be a collection of TabItem. See this page on SO for more: This above is for WPF but it should be the same in Avalonia. |
Beta Was this translation helpful? Give feedback.
-
This is odd. You have defined a items source and a content for the tab control. Normally you do one or the other. Which is also probably why you have an error. |
Beta Was this translation helpful? Give feedback.
-
Thanks a lot for your explanation! Since each tabbed panel has a fairly complex structure, I decided to create a dedicated view for each. I now create the ViewModels for each panel in the code-behind of the MainViewModel, and define the DataTemplates within the UserControl of the MainView (see below). Like you, I prefer to keep these definitions as close as possible to the place I use them. Currently, I do not see an advantage keeping them in a separate resource dictionary. <UserControl.DataTemplates>
<DataTemplate DataType="models:CoordinatesTabViewModel">
<views:CoordinatesTabView/>
</DataTemplate>
<DataTemplate DataType="models:DiagTabViewModel">
<views:DiagTabView/>
</DataTemplate>
<DataTemplate DataType="models:SatellitesTabViewModel">
<views:SatellitesTabView/>
</DataTemplate>
</UserControl.DataTemplates>
<TabControl ItemsSource="{Binding Tabs}" SelectedItem="{Binding SelectedTab}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}" />
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl> I now derive all ViewModels from a ViewModelBase class, which only contains the Header attribute used as a title of the tabbed panel (a bit unfortunate; maybe I should call this class ViewModelTabbedPanel, to avoid that each ViewModel finally ends up with a Header). |
Beta Was this translation helpful? Give feedback.
Nope. In fact, doing that would be a major MVVM violation. When binding to an items control from a view model, you generally don't have to worry about the container control. The control will set it up for you.
You can either use a ViewLocator, or you need to specify a DataTemplate.
https://docs.avaloniaui.net/docs/concepts/view-locator
https://docs.avaloniaui.net/docs/basics/data/data-templates
I would su…