Silverlight TreeView ScrollViewer问题

时间:2010-08-03 19:10:07

标签: silverlight silverlight-3.0 treeview scrollviewer

嘿SO,在Silverlight中有一个关于TreeView控件的问题。

我有一个动态添加元素到树视图的应用程序。一些元素足够长,需要水平滚动。当它们被添加到树视图中时,我的树视图一直保持正确向左滚动,因此您必须滚动才能看到项目的结尾。但是,如果我单击其中一个项目(隐藏树视图),然后使用我实现的“返回结果”按钮(注意这只涉及可见性更改)树视图变为可见,它会自动滚动到中心。

当我回到结果时,有谁知道如何让树视图一直向左滚动?

我试过搞乱树视图模板:

<Style TargetType="controls:TreeView" x:Name="SCREW">
            <Setter Property="Background" Value="#FFFFFFFF" />
            <Setter Property="Foreground" Value="#FF000000" />
            <Setter Property="HorizontalContentAlignment" Value="Left" />
            <Setter Property="VerticalContentAlignment" Value="Top" />
            <Setter Property="Cursor" Value="Arrow" />
            <Setter Property="BorderThickness" Value="1" />
            <Setter Property="Padding" Value="1" />
            <Setter Property="BorderBrush" Value="#FF000000" />
            <Setter Property="IsTabStop" Value="True" />
            <Setter Property="TabNavigation" Value="Once" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="controls:TreeView" x:Name="SCREWTEMPLATE">
                        <Grid>
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal" />
                                    <VisualState x:Name="MouseOver" />
                                    <VisualState x:Name="Pressed" />
                                    <VisualState x:Name="Disabled" />
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="FocusStates">
                                    <VisualState x:Name="Unfocused" />
                                    <VisualState x:Name="Focused" />
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="ValidationStates">
                                    <VisualState x:Name="Valid" />
                                    <VisualState x:Name="InvalidUnfocused">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Validation" Storyboard.TargetProperty="Visibility">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Visible" />
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="InvalidFocused">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Validation" Storyboard.TargetProperty="Visibility">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Visible" />
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationToolTip" Storyboard.TargetProperty="IsOpen">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <System:Boolean>True</System:Boolean>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>

                            <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="2">
                                <Border Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}" Margin="1">
                                    <ScrollViewer x:Name="ScrollViewer" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Background="{x:Null}" BorderBrush="Transparent" BorderThickness="0" IsTabStop="False" TabNavigation="Once" Loaded="ScrollViewer_Loaded">
                                        <ItemsPresenter Margin="5" />
                                    </ScrollViewer>
                                </Border>
                            </Border>

                            <Border x:Name="Validation" Grid.Column="1" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="#FFDB000C" CornerRadius="2" Visibility="Collapsed">
                                <ToolTipService.ToolTip>
                                    <ToolTip x:Name="ValidationToolTip" Placement="Right" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" IsHitTestVisible="True" />
                                </ToolTipService.ToolTip>
                                <Grid Width="10" Height="10" HorizontalAlignment="Right" Margin="0,-4,-4,0" VerticalAlignment="Top" Background="Transparent">
                                    <Path Margin="-1,3,0,0" Fill="#FFDC000C" Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 Z" />
                                    <Path Margin="-1,3,0,0" Fill="#FFFFFFFF" Data="M 0,0 L2,0 L 8,6 L8,8" />
                                </Grid>
                            </Border>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

但问题是我不知道如何从后面的代码访问ScrollViewer ...所以我不能调用ScrollView.setScrollOffset(0d,0d)或类似的东西。

有什么想法吗?万分感谢。

最后一件事,我想尽量避免实现扩展treeview的新控件。我真的希望有一种方法可以访问/修改和使用与c#codebehind控件模板相关的函数。

2 个答案:

答案 0 :(得分:0)

我只是为此设置了一个附加属性,并在那里创建你想要的逻辑。然后,您将使用附加属性装饰您的树视图。我们对包含滚动查看器的其他控件执行类似的操作:

public class ScrollResetService
{
    public static DependencyProperty IsScrollResetProperty = DependencyProperty.RegisterAttached("IsScrollReset",
                                                                                                 typeof(bool),
                                                                                                 typeof(ScrollResetService),
                                                                                                 new PropertyMetadata(false,
                                                                                                      OnIsScrollResetChanged));
    public static void SetIsScrollReset(DependencyObject d, bool value)
    {
        d.SetValue(IsScrollResetProperty, value);
    }

    public static bool GetIsScrollReset(DependencyObject d)
    {
        return d.GetValue(IsScrollResetProperty) == null ? false : (bool)d.GetValue(IsScrollResetProperty);
    }

    private static void OnIsScrollResetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var treeView = d as TreeView;
        bool isScrollReset;
        if (e.NewValue!= null && bool.TryParse(e.NewValue.ToString(), out isScrollReset) && treeView != null)
        {

            treeView.SelectedItemChanged += (sender, args) =>
                                               {
                                                   var scrolls =
                                                       treeView.GetAllLogicalChildrenOfType<IScrollInfo>();
                                                   scrolls.ForEach(i => i.SetVerticalOffset(0));
                                               };

        }
    }

}

public static class Extensions
    {

public static IEnumerable<T> GetAllLogicalChildrenOfType<T>(this FrameworkElement parent)
        {
            Debug.Assert(parent != null, "The parent cannot be null.");
            return parent.GetVisualChildren().Flatten(item => item.GetVisualChildren()).OfType<T>();
        }

public static IEnumerable<T> Flatten<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> childSelector)
        {
            if (items == null) return Enumerable.Empty<T>();
            return items.Concat(items.SelectMany(i => childSelector(i).Flatten(childSelector)));
        }

internal static IEnumerable<DependencyObject> GetVisualChildren(this DependencyObject parent)
        {
            int childCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int counter = 0; counter < childCount; counter++)
            {
                yield return VisualTreeHelper.GetChild(parent, counter);
            }
        }
}

答案 1 :(得分:0)

在处理SelectedItemChanged的{​​{1}}事件后,我将此代码置于行为中(在代码后面也会起作用):

TreeView

需要var offset = this.HorizontalScrollOffsetAfterSelect; // would be 0 if you don't want to make that adjustable if (!Double.IsNaN(offset)) { var scrollViewer = trv.GetVisualDescendants().OfType<ScrollViewer>().FirstOrDefault(); if (scrollViewer != null) { scrollViewer.ScrollToHorizontalOffset(offset); // and because that wasn't enough because of timing issues: var scrollBar = scrollViewer.GetVisualDescendants().OfType<ScrollBar>().Where(cur => cur.Orientation == Orientation.Horizontal).FirstOrDefault(); if (scrollBar != null) { RoutedPropertyChangedEventHandler<double> handler = null; handler = (sender, e) => { scrollBar.ValueChanged -= handler; scrollViewer.ScrollToHorizontalOffset(offset); }; scrollBar.ValueChanged += handler; } } } using System.Linq;以及工具包ofc。

到目前为止,对我来说效果还不错。