-1

I have a wpf application with a tab control showing images instead of text on the tabitem. Now I want to rewrite the whole thing and use prism. I found an example but there is only a text property bound to the tabitem. How can I display an image through binding to a viewmodel (Each module has one tab).

1 Answers1

0

When binding the items to the TabControl, use ItemsSource. The ItemTemplate defines what is shown in the tab header. The ContentTemplate defines what is shown in the tab area.

View Models

public class ShellViewModel : BindableBase
{
    public ObservableCollection<ItemViewModel> Items
    {
        get;
    } = new ObservableCollection<ItemViewModel>();

    public ShellViewModel()
    {
        Items.Add(new ItemViewModel { Name = "First", ImageUri = new Uri("http://placehold.it/50x50") });
        Items.Add(new ItemViewModel { Name = "Second", ImageUri = new Uri("http://placehold.it/40x40") });
        Items.Add(new ItemViewModel { Name = "Third", ImageUri = new Uri("http://placehold.it/30x30") });
    }
}

public class ItemViewModel : BindableBase
{
    private string _name;
    private Uri _imageUri;

    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    public Uri ImageUri
    {
        get => _imageUri;
        set => SetProperty(ref _imageUri, value);
    }
}

View

<Window x:Class="WpfApp4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp4"
    xmlns:viewModels="clr-namespace:WpfApp4.ViewModels"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <viewModels:ShellViewModel />
</Window.DataContext>
<Grid>
    <TabControl ItemsSource="{Binding Items}">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <Image Source="{Binding ImageUri}" Height="20"></Image>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Name}"></TextBlock>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Grid>

The above code will show three (3) tabs with the specified image in the tab header. I've dummied up the content with just text.

Eric
  • 1,737
  • 1
  • 13
  • 17
  • Thanx. I know how to do it when I create tabitems myself by code or xaml. But my question was about PRISM. The tabitems are created by PRISM on navigating to a view. – Nick Burger Nov 15 '17 at 22:11