Here is my answer to a similar question where you can found an extended TabControl and an example of code.
So now I focus on your particular implementation.
In this example a TabControl
is bound to the Items
property, a menu List - to the MenuItems
property.
public class MainViewModel
{
public MainViewModel()
{
MenuItems = new ObservableCollection<string>(){ "Item 1", "Item 2", "Item 3"};
this.Items = new ObservableCollection<TabItemViewModel>
{
new TabItemViewModel("Tab 1", OnItemRequestClose),
new TabItemViewModel("Tab item 2", OnItemRequestClose)
};
}
public ObservableCollection<string> MenuItems { get; set; }
public string CurrentMenuItem
{
get { return currentMenuItem; }
set
{
currentMenuItem = value;
OnPropertyChanged("CurrentMenuItem");
this.OnMenuChanged();
}
}
public ObservableCollection<TabItemViewModel> Items { get; set; }
public void OnItemRequestClose(TabItemViewModel item)
{
this.Items.Remove(item);
}
}
XAML:
<ListBox ItemsSource="{Binding MenuItems}"
SelectedItem="{Binding CurrentMenuItem, Mode=TwoWay}" />
You can use a command bound to the SelectionChanged
event, but my solution is more universal.
An implementation of the method OnMenuChanged
:
private void OnMenuChanged()
{
if(this.CurrentMenuItem == "Item 1")
{
var addItem = new TabItemViewModel("Item 1", OnItemRequestClose);
addItem.Content = new SomeView() { DataContext = new SomeViewModel() };
this.Items.Add(addItem);
}
//and so on, and so forth
}
I used this solution in a real-world application, so you can be sure that it works without problems.