0

I have the following TabControl:

<TabControl x:Name="Networks">
  <TabControl.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding DisplayName}" />
        <Button Content="X" cal:Message.Attach="CloseItem($dataContext)" />
      </StackPanel>
    </DataTemplate>
  </TabControl.ItemTemplate>
</TabControl>

As you can see it is bound to a ViewModel using Caliburn.Micro, but I think this is unrelevant. How would I add a button on to this control on the right side to add new TabItems? I'm looking for simple solution. I've searched for this but I haven't found an easy implementation of this.

Thanks

errorcode007
  • 321
  • 1
  • 4
  • 11
  • 1
    Possible duplicate of http://stackoverflow.com/questions/3468866/wpf-tabcontrol-add-new-tab-button ? – snurre Jan 02 '12 at 14:08

1 Answers1

2

You could make the ItemsSource a CompositeCollection with a CollectionContainer for the tabs at the beginning and one explicit TabItem at the end which can add a new item on click (a +-tab as in some browsers).

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • I've tried this, but the binding doesn't seem to work. I have a BindableCollection, I've read that you can only bind freezable collections. – errorcode007 Jan 02 '12 at 14:00
  • @errorcode007: There is no `DataContext` in a `CollectionContainer` and you cannot use `ElementName` or `RelativeSource` either ([see this question](http://stackoverflow.com/questions/6446699/how-do-you-bind-a-collectioncontainer-to-a-collection-in-a-view-model)). You could of course create the collection in the VM and work with simple assignments. – H.B. Jan 02 '12 at 14:11
  • @errorcode007: Also `IEditableCollectionView` is for just this use-case, see the duplicate linked to in the comment, there's a better solution than this. – H.B. Jan 02 '12 at 14:18
  • What's the best way to handle `SelectedItem` using this solution? I'm currently getting errors when I click on the new tab because it's trying to convert my explicit `TabItem` into the type the `ItemSource` of the `CompositeCollection` is bound to. – Nathan Friend Nov 04 '13 at 17:15
  • 1
    @NathanFriend: Not sure, maybe you can set some properties on the `TabItem` to make it un-selectable (disable parts/focusability, things like that). Alternatively you could bind to property of type `object` and create another properly typed property that returns ` as `, so that will just be `null` for the new item tab. – H.B. Nov 05 '13 at 00:54
  • Thanks, @H.B. I ended up specifying a converter that returned `null` when the binding attempted to convert the static item into the bound list's data type. – Nathan Friend Nov 07 '13 at 18:45