Closed rasta-mouse closed 9 months ago
Don't store control instances in your ViewModels. Use the HeaderTemplate
and ContentTemplate
to control the view from a ViewModel:
<ui:TabView IsAddTabButtonVisible="False"
TabCloseRequested="TabView_TabCloseRequested"
CanDragTabs="True" CanReorderTabs="True"
TabItems="{Binding TabView}"
SelectedItem="{Binding SelectedTab}">
<ui:TabView.TabItemTemplate>
<DataTemplate DataType="local:TabItem">
<ui:TabViewItem IconSource="{Binding IconSource}"
Header="{Binding }"
Content="{Binding }">
<ui:TabViewItem.HeaderTemplate>
<DataTemplate DataType="local:TabItem">
<controls:MyCustomHeader />
</DataTemplate>
</ui:TabViewItem.HeaderTemplate>
<ui:TabViewItem.ContentTemplate>
<DataTemplate DataType="local:TabItem">
<controls:MyCustomContent />
</DataTemplate>
</ui:TabViewItem.ContentTemplate>
</ui:TabViewItem>
</DataTemplate>
</ui:TabView.TabItemTemplate>
</ui:TabView>
If you need more control over specific control views for each tab, then you need to wrap your headers and content ViewModels in their own classes and create DataTemplates for each. Read up and familiarize yourself with how MVVM works:
public class TabItemViewModel
{
public TabItemHeaderBase Header { get; }
public TabItemContentBase Content { get; }
}
// Base classes for TabItem headers and contents - derived classes can add extra functionality
public class TabItemHeaderBase
{
}
public class TabItemContentBase
{
}
Create DataTemplates to support each of these:
<Window.DataTemplates>
<DataTemplate DataType="vm:TabItemHeader1">
....
</DataTemplate>
...
</Window.DataTemplates>
Then just adjust your TabView like:
<ui:TabView IsAddTabButtonVisible="False"
TabCloseRequested="TabView_TabCloseRequested"
CanDragTabs="True" CanReorderTabs="True"
TabItems="{Binding TabView}"
SelectedItem="{Binding SelectedTab}">
<ui:TabView.TabItemTemplate>
<DataTemplate DataType="local:TabItem">
<ui:TabViewItem IconSource="{Binding IconSource}"
Header="{Binding Header}"
Content="{Binding Content}">
</ui:TabViewItem>
</DataTemplate>
</ui:TabView.TabItemTemplate>
</ui:TabView>
Ahhh, yes I understand. I see now that my question was pretty stupid 😥 Thanks for taking the time to provide such a detailed response.
I have quite a basic
TabView
, which looks something like this:Instead of a simple string as my
Header
, I'm using a customUserControl
in an effort to show more dynamic content. MyTabItem
class looks like this:The header renders as intended and you can switch between tabs just fine. However, the application will crash if you try to re-order them. The full stack trace is:
I'm running Avalonia UI 11.0.6 and FluentAvaloniaUI 2.0.4 on Windows 11.
Any guidance would be appreciated.