C#/WPF : Why is tab not focusing properly

标签 c# wpf mvvm collectionviewsource

我有一个标签控件

<TabControl Height="Auto" Grid.Row="1" ItemsSource="{Binding Tabs}" IsSynchronizedWithCurrentItem="True">

绑定(bind)到 ViewModel 中的 Tabs。我还使用 CollectionViewSource 来聚焦选项卡

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 > 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;
}

当我有超过 1 个标签时,当我创建新标签时,标签会正确聚焦

alt text

当没有标签时,新标签似乎没有正确聚焦。注意选项卡标题

alt text

我该如何解决这个问题?或者是什么导致了这种行为?显示了文本框(选项卡内容),但标题不像其选择的那样呈现

更新

它适用于新文件/项目...嗯...一定是一些相关代码...我可能会重做那部分...

最佳答案

IsSynchronizedWithCurrentItem="True" 没有任何意义,除非您将 TabControl.ItemsSource 绑定(bind)到 ICollectionView

我不知道将您的绑定(bind)从 ObservableCollection 更改为 ICollectionView 是否会解决您的问题,但这就是我设置数据绑定(bind) tabcontrol 的方式。

另一种方法是公开一个新属性

public TabViewModel CurrentTabViewModel
{
    get
    {
        return _tabs.CurrentItem as TabViewModel:
    }
    set
    {
        _tabs.MoveCurrentTo(value);
    }
}

并将 TabControl 的 SelectedItem 绑定(bind)到 CurrentTabViewModel

<TabControl SelectedItem="{Binding Path=CurrentTabViewModel}" ... />

关于C#/WPF : Why is tab not focusing properly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3983824/

相关文章:

c# - 关于响应式设计的一些建议

c# - 避免 datagridview 的按钮点击/控件;自动显示

ItemsControl 上的 WPF MVVM 单选按钮

c# - WinRT FlipView.SelectedIndex 绑定(bind)不响应 ViewModel 中的更改

c# - 将对象从父 View 传递到 MVVM 中的 subview

wpf - TreeView 绑定(bind)到 View 模型不起作用

c# - 如何从字符串中提取所有数字(如 int)? C#

c# - 创建新的多维数组并用其他数组的值填充它

.NET WPF 窗口淡入淡出动画

.net - 如何为基于 ItemsControl 的控件(如 ListView 或 DataGrid)定义 Empty DataTemplate