C#/WPF: Why is tab not focusing properly
I have a tab control
<TabControl Height="Auto" Grid.Row="1" ItemsSource="{Binding Tabs}" IsSynchronizedWithCurrentItem="True">
That is bound to Tabs
in the ViewModel
. I also used CollectionViewSource
to focus tabs
protected ObservableCollection<TabViewModel> _tabs;
protected ICollectionView _tabsViewSource;
public ObservableCollection<TabViewModel> Tabs
{
get { return _tabs; }
}
public void OnTabsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null && e.NewItems.Count &开发者_StackOverflow社区gt; 0)
foreach (TabViewModel tab in e.NewItems)
{
tab.CloseRequested += OnCloseRequested;
_tabsViewSource.MoveCurrentTo(tab); // focus newly created tab
}
if (e.OldItems != null && e.OldItems.Count > 0)
foreach (TabViewModel tab in e.OldItems)
tab.CloseRequested -= OnCloseRequested;
}
When I have more that 1 tab, when I create new Tabs, tabs are focused properly
when there are no tabs, new tabs don't seem to be focused properly. notice the tab header
how might I fix this? or what is causing this behavior? the text box (tab content) is shown but the header don't render like its selected
UPDATE
It works with a fresh file/project ... hmm ... must be some related code ... I might redo that part ...
IsSynchronizedWithCurrentItem="True"
has no meaning unless you bind your TabControl.ItemsSource
to an ICollectionView
.
I can't tell if changing your binding from ObservableCollection to ICollectionView will solve your problem, but that is how I have setup my databound tabcontrol.
An alternative could be to expose a new property
public TabViewModel CurrentTabViewModel
{
get
{
return _tabs.CurrentItem as TabViewModel:
}
set
{
_tabs.MoveCurrentTo(value);
}
}
and bind TabControl's SelectedItem
to CurrentTabViewModel
<TabControl SelectedItem="{Binding Path=CurrentTabViewModel}" ... />
Without the code, that initializes the single-tab-collection, it's just guessing. A Workaround for you would be setting SelectedIndex of the tabView = 0 -> first tab is selected initially.
<TabControl Height="Auto"
Grid.Row="1"
ItemsSource="{Binding Tabs}"
IsSynchronizedWithCurrentItem="True"
SelectedIndex="0">
精彩评论