2017-02-27 21 views
1

我有一個窗口有一些控件。在這些控件中,我有一個內容控件,用於打開多個視圖。此內容控件位於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中進行更改)。謝謝

+0

即使有一個明確的說法 - 代碼分離,你應該被允許使用之類的東西'AttachedProperty'爲了一些代碼僅查看關注。 – grek40

回答

0

在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) 
    { 
     ... 
    } 
}; 
0

您可以在視圖模型添加一個布爾屬性指示該視圖需要滾動查看器,並通過一些轉換器將其綁定到'VerticalScrollBarVisibility',以將bool轉換爲禁用/自動。

服用點,如:

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