Search code examples
c#wpfbindingtabitem

WPF Binding ListBox and TabItems


New to WPF, am trying to do something basic (I think!). I have a TabControl and a ListBox that shows what tabitems are open:

<ListBox Width="170" Height="188" ItemsSource="{Binding Items, ElementName=tabControl}" Name="ListTabs" Canvas.Left="0" Canvas.Top="27">
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                    El
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Header}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Is it possible to bind to specific tabitems (tabitem2 and tabitem3) rather than the whole tabcontrol? Reason being is the first tabitem1 is a welcome tab and I don't want it to be shown in the listbox.

UPDATE:

Would someone be so kind to post some code on how to use an IValueConverter to hide/filter a tabitem? I have been searching for hours with no luck. Many many thanks!


Solution

  • In your current set up the only way would be to run it through an IValueConverter.

        <Window.Resources>
            <converters:StripOutFirstTabConverter x:Key="StripOutFirstTabConverter"/>
        </Window.Resources>
    
        <ListBox Width="170" Height="188" ItemsSource="{Binding Items, ElementName=tabControl, Converter={StaticResource StripOutFirstTabConverter}}" Name="ListTabs" Canvas.Left="0" Canvas.Top="27">
                <ListBox.ItemContainerStyle>
                    <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                        El
                    </Style>
                </ListBox.ItemContainerStyle>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Header}"/>
                    </DataTemplate>
                </ListBox.ItemTemplate>
         </ListBox>
    

    If you were willing to modify your approach you could bind the ListBox.ItemsSource to a ICollectionView and then make use of the Filter property.

    public ICollectionView Tabs
    {
        get 
        {
            if (_view == null)
            {
                _view = CollectionViewSource.GetDefaultView(tabControl.Items);
                _view.Filter = Filter;
            }
    
            return _view;
        }
    }
    
    private bool Filter(object arg)
    {
        //arg will be a TabItem, return true if you want it, false if you don't
    }