Home > Blockchain >  How to change TabView Header Template in WinUI 3 when bound to collection?
How to change TabView Header Template in WinUI 3 when bound to collection?

Time:10-15

I'm trying to modify the WinUI 3 default TabItem Header Text to Icon Text while its bound via TabItemsSource like so:

    <TabView Grid.Column="1" DataContext="{x:Bind ReportViewModel}"
             TabItemsSource="{x:Bind ReportViewModel.ReportTabSources}"
             TabCloseRequested="{x:Bind ReportViewModel.TabClosedRequest}"
             TabWidthMode="SizeToContent"
             IsAddTabButtonVisible="False"
             CanDragTabs="False"
             CanReorderTabs="False">
        <TabView.TabItems>
            <TabViewItem>
                <TabViewItem.IconSource>
                    <SymbolIconSource Symbol="Document" />
                </TabViewItem.IconSource>
                <TabViewItem.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding}"></TextBlock>
                    </DataTemplate>
                </TabViewItem.HeaderTemplate>
            </TabViewItem>
        </TabView.TabItems>
    </TabView>

ReportTabSources is a ReadOnlyObservableCollection that contains a following Model:

public class ReportTabSource
{
    public string? Name
    {
        get; set;
    }
    public long Id
    {
        get; set;
    }
    public Report Report
    {
        get;
        set;
    }

    public override string ToString() => Name;
}

But the Icon Text isn't shown anywhere within the TabItemHeader...

How to fix this?

CodePudding user response:

You can set the header template like this.

<TabView
    Grid.Column="1"
     DataContext="{x:Bind ReportViewModel}"
     TabItemsSource="{x:Bind ReportViewModel.ReportTabSources}"
     TabCloseRequested="{x:Bind ReportViewModel.TabClosedRequest}"
     TabWidthMode="SizeToContent"
     IsAddTabButtonVisible="False"
     CanDragTabs="False"
     CanReorderTabs="False">
    <TabView.Resources>
        <Style TargetType="TabViewItem">
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate x:DataType="local:ReportTabSource">
                        <StackPanel Orientation="Horizontal">
                            <SymbolIcon Symbol="Document" />
                            <TextBlock Text="{x:Bind Name}" />
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TabView.Resources>
</TabView>
  • Related