c# - WPF - 如何停止 TabControl 在 MouseUp 事件中更改索引?

标签 c# wpf

我有一个带有多个 TabItem 的 ItemsSource 的 TabControl,以及一个将新 TabItem 添加到此列表的附加 TabItem。负责添加项目的 TabItem 监听 MouseUp 事件。 问题是,在添加项目后我更新了 SelectedIndex,但随后 SelectedIndex 更改为我单击的元素。

XAML 的一部分:

<TabControl ItemsSource="{Binding Tabs}" SelectedIndex="{Binding SelectedIndex}">

我的代码:

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

编辑:基于答案的最终代码(仅相关部分):

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

最佳答案

您需要使用 DependencyProperty , 或 INotifyPropertyChanged , 因为绑定(bind)引擎不知道 SelectedIndex 的变化属性(property)。

public static readonly DependencyProperty SelectedIndexProperty = DependencyProperty.Register(
    "SelectedIndex",
    typeof(int),
    typeof(WhateverYourClassNameIs));

public int SelectedIndex
{
    get { return (int)GetValue(SelectedIndexProperty); }
    set { SetValue(SelectedIndexProperty, value); }
}

或者,你可以让这个类实现INotifyPropertyChanged , 但通常用于已经从 FrameworkElement 派生的类(带 UI 的类),DependencyProperty将是首选。

关于c# - WPF - 如何停止 TabControl 在 MouseUp 事件中更改索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38369497/

相关文章:

c# - WPF如何访问相关控件中的ValidationResult对象?

c# - WPF/C# 取消 DoWork 外部的 BackgroundWorker 调用

wpf - Caliburn 3 看不到 View

方法中的 C# 默认值 - 编译错误 : compile-time constant

c# - 修复网络浏览器内容的不同文本量

c# - 如何在 C# 中使用 datetimepicker 将日期(长格式)插入到 Access 数据库中? (错误仅在日期部分)

c# - 使用 DPAPI (Data Protector API) 取消保护不同计算机上的数据

c# - WPF C# UIControl 像 iPhone 菜单图标一样摆动

c# - Entity Framework 有时不加载子对象/集合的内容

c# - Json 从 JSON 对象 C# 中获取数组对象