Search code examples
c#wpfxamlribbon

Detect if the active tab has changed in Microsoft Ribbon


I would like to be able to tell, which tab is the active one in Microsoft Ribbon to change the content presentation accordingly.

How can I do that?

Here's what I came up with:

    public MainWindow()
    {
        InitializeComponent();

        // Insert code required on object creation below this point.
        new Thread(() =>
        {
            int lastIndex = int.MinValue;

            while (true)
            {
                Thread.Sleep(100);

                int newIndex = -1;
                this.Dispatcher.Invoke(DispatcherPriority.Normal,
                    new Action(() =>
                    {
                        newIndex = Ribbon.SelectedIndex;
                    }));

                if (newIndex != lastIndex)
                {
                    lastIndex = newIndex;
                    var index = lastIndex;
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) (() =>OnCurrentTabChanged(index)));
                }
        }){ IsBackground=true}.Start();
    }

    void OnCurrentTabChanged(int tabIndex)
    {

    }

but there must be a better way to do this. Is there?


Solution

  • Ribbon is inheriting from ItemsControl as a result of that if you bind to SelectedItem property you will get notifications about current Tab changing.