I have a TabControl with an ItemsSource of multiple TabItems, and an additional TabItem that adds new TabItems to this list. The TabItem responsible for adding an item listens to the MouseUp event. The problem is, that after adding an item I update the SelectedIndex, but then the SelectedIndex changes to the element I've clicked on.
Part of the XAML:
<TabControl ItemsSource="{Binding Tabs}" SelectedIndex="{Binding SelectedIndex}">
My code:
public ObservableCollection<TabItem> Tabs { get; set; }
public int SelectedIndex { get; set; }
private void Tab_add_MouseUp(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
int count = Tabs.Count;
TabItem tabItem = new TabItemDepartment("Header #x");
Tabs.Insert(count - 1, tabItem);
SelectedIndex = count - 2;
}
edit: Final code (only relevant parts) based on answers:
public class CalendarViewModel : INotifyPropertyChanged
{
public ObservableCollection<TabItem> Tabs { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private int _SelectedIndex;
public int SelectedIndex
{
get
{
return _SelectedIndex;
}
set
{
_SelectedIndex = value;
NotifyPropertyChanged(nameof(SelectedIndex));
}
}
private void Tab_add_MouseDown(object sender, MouseButtonEventArgs e)
{
TabItem tabItem = new TabItemDepartment("Header #x");
Tabs.Insert(Tabs.Count - 1, tabItem);
SelectedIndex = Tabs.Count - 2;
e.Handled = true;
}
protected void NotifyPropertyChanged(string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
e.Handled
stops the event from routing down, then it should work. – Jai