Question

I have a tab control that only responds to changing tabs with the mouse click.

Do I need to manually code in an event handler for tab control despite having the Surface SDK? Or is there a better control handler that I could use here?

I feel like this is entirely counter productive to the point of having the SDK. Especially because I plan on having a lot of different, unique tabs in my program and don't want to be handling each tab individually with nested ifs in a button_TouchDown function. I already have custom buttons that that have button_TouchDown setup and adding individual tab controls would be a headache and hell of a mess of code.

I tried searching but came up empty handed which makes me think that perhaps I am missing something and it should work. Is it because I have a predefined button_TouchDown function?

Was it helpful?

Solution

private void TabItem_TouchDown(object sender, TouchEventArgs e)
    {
        TabItem tab = sender as TabItem;
        TabControl control = tab.Parent as TabControl;
        control.SelectedItem = tab;
        e.Handled = true;
    }

XAML

 <TabItem x:Name="hccontactTab" Header="Phone" TouchDown="TabItem_TouchDown">

OTHER TIPS

Based on the above answer, but enhanced to account for scrolling per touch. Use a ClassHandler to handle this cleanly within your application (I use AutoFac's IStartable to auto-register it during building the container):

using System.Windows;
using System.Windows.Controls;
using Autofac;

namespace ...ClassHandlers
{
    public class TabItemTouchClassHandler : IStartable
    {
        public void Start()
        {
            Register();
        }

        public void Register()
        {
            EventManager.RegisterClassHandler(typeof(TabItem), UIElement.TouchDownEvent, new RoutedEventHandler(OnTabItemTouchDown));
        }

        //must be static! otherwise memory leaks!
        private static void OnTabItemTouchDown(object ender, routedEventArgs e)
        {
            var tab = sender as TabItem;
            var control = tab?.Parent as TabControl;
            if (control != null && !Equals(tab, control.SelectedItem))
            {
                control.SelectedItem = tab;
                e.Handled = true;
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top