在scrollviewer中显示活动选项卡

时间:2014-07-22 12:27:10

标签: c# wpf tabcontrol

我的tabcontrol中有很多标签,所以我使用了want to make scrollable tabs for a tabcontrol的解决方案。 问题是在我的窗口中我有按钮Previous-Next,它改变了活动标签。所以我想将scrollviewer自动移动到活动标签。可以使用BringIntoView()的{​​{1}}方法进行制作。但是我怎么能在我的情况下实现呢?

1 个答案:

答案 0 :(得分:1)

在这里,我通过创建附加行为(Attached Properties

解决了这个问题

如果您的模板类似于您发布的链接

添加以下样式,并将附加属性ScrollHelper.SelectScroll绑定到标签项的IsSelected

    <TabControl>
        <TabControl.Resources>
            <Style TargetType="TabItem" xmlns:l="clr-namespace:CSharpWPF">
                <Setter Property="l:ScrollHelper.SelectScroll"
                        Value="{Binding IsSelected,RelativeSource={RelativeSource Self}}" />
            </Style>
        </TabControl.Resources>
        ...
    </TabControl>

行为类

namespace CSharpWPF
{
    class ScrollHelper : DependencyObject
    {
        public static bool GetSelectScroll(DependencyObject obj)
        {
            return (bool)obj.GetValue(SelectScrollProperty);
        }

        public static void SetSelectScroll(DependencyObject obj, bool value)
        {
            obj.SetValue(SelectScrollProperty, value);
        }

        // Using a DependencyProperty as the backing store for SelectScroll.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectScrollProperty =
            DependencyProperty.RegisterAttached("SelectScroll", typeof(bool), typeof(ScrollHelper), new PropertyMetadata(false, OnSelectScroll));


        private static void OnSelectScroll(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            TabItem tab = d as TabItem;
            if ((bool)e.NewValue)
            {
                tab.BringIntoView();
            }
        } 
    }
}

更改属性后,它将调用BringIntoView()方法,该方法将选项卡拉入视图,因此scrollviewer将滚动到选项卡

您可以根据自己的喜好选择重命名该属性或类,我只是选择了一个随机名称。

相关问题