【问题标题】:Disable Parent’s ScrollViewer from Child从子级禁用父级的 ScrollViewer
【发布时间】:2017-02-27 11:37:34
【问题描述】:

我有一个带有一些控件的窗口。在这些控件中,我有一个内容控件,用于打开多个视图。此内容控件位于 ScrollViewer 下。如下代码:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="350"
        Width="525">
    <Grid>
        <ScrollViewer Grid.Row="2"
                      VerticalScrollBarVisibility="Disabled" 
                      HorizontalScrollBarVisibility="Auto">
            <ContentControl x:Name="ActiveItem" 
                            HorizontalContentAlignment="Stretch"
                            VerticalContentAlignment="Stretch"/>
        </ScrollViewer>
    </Grid>
</Window>

我们有不同的视图,我们过去通过将它们设置为 ActiveItem 来打开它们。在一个视图中,我想禁用父级的 ScrollViewer。有没有可能的方法? (只能在 View 的 XAML 中进行更改)。谢谢

【问题讨论】:

  • 即使有清晰的视图 - 代码分离,您也应该被允许使用 AttachedProperty 之类的东西来编写一些仅限视图的问题。

标签: wpf xaml


【解决方案1】:

在 XAML 中?不。XAML 是一种 标记 语言,仅此而已。

但您可以使用以下方法在可视化树中找到父 ScrollViewer 元素:

public static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    var parent = VisualTreeHelper.GetParent(dependencyObject);

    if (parent == null) return null;

    var parentT = parent as T;
    return parentT ?? FindParent<T>(parent);
}

用法:

ActiveItem.Loaded += (s, e) => 
{
    ScrollViewer sv = FindParent<ScrollViewer>(ActiveItem);
    if (sv != null)
    {
        ...
    }
};

【讨论】:

    【解决方案2】:

    您可以在视图模型中添加一个 bool 属性来指示哪个视图需要滚动查看器,并使用一些转换器将其绑定到“VerticalScrollBarVisibility”,以将 bool 转换为 Disabled/Auto。

    有点像:

    <ScrollViewer Grid.Row="2"
                          VerticalScrollBarVisibility="{Binding IsScrollNeeded, Converter={StaticResource someConverter}}" 
                          HorizontalScrollBarVisibility="Auto">
                <ContentControl x:Name="ActiveItem" 
                                HorizontalContentAlignment="Stretch"
                                VerticalContentAlignment="Stretch"/>
            </ScrollViewer>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多