2017-02-17 82 views
4

我有一個GridView一個ListView內:ListView ComputedVerticalScrollBarVisibilityProperty總是返回可見?

<ListView>      
    <ListView.View> 
    <GridView> 
     <GridViewColumn Width="100" />    
     <GridViewColumn Width="130" />    
     <GridViewColumn Width="130" />   
    </GridView> 
    </ListView.View> 
</ListView> 

我想檢測時垂直滾動條是對用戶可見。

出於某種原因,這行代碼總是返回Visible,即使滾動條是不可見的: listView.GetValue(ScrollViewer.ComputedVerticalScrollBarVisibilityProperty)

我在做什麼錯在這裏?

回答

2

因爲您正在查找的值位於ListBox的內部ScrollViewer中。

你可以像這樣得到它的價值:

(使用How to get children of a WPF container by type?

XAML:

<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" 
     Title="MainWindow" 
     Width="525" 
     Height="350" 
     mc:Ignorable="d"> 
    <Grid> 

     <ListBox x:Name="Box"> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
      <ListBoxItem>abcd</ListBoxItem> 
     </ListBox> 

    </Grid> 
</Window> 

代碼:

using System.Diagnostics; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Media; 

namespace WpfApplication1 
{ 
    public partial class MainWindow 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      SizeChanged += MainWindow_SizeChanged; 
     } 

     private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e) 
     { 
      var viewer = GetChildOfType<ScrollViewer>(Box); 
      if (viewer != null) 
      { 
       Debug.WriteLine(viewer.ComputedVerticalScrollBarVisibility); 
      } 
     } 

     public static T GetChildOfType<T>(DependencyObject depObj) 
      where T : DependencyObject 
     { 
      if (depObj == null) 
       return null; 

      for (var i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) 
      { 
       var child = VisualTreeHelper.GetChild(depObj, i); 

       var result = child as T ?? GetChildOfType<T>(child); 
       if (result != null) 
        return result; 
      } 
      return null; 
     } 
    } 
} 

你可以看並使用研究您的WPF應用程序事件和屬性。

+0

我使用的是ListView而不是ListBox - 我還需要GetChildOfType方法嗎? –

+1

恐怕是的,因爲這是你如何獲得內部ScrollViewer,因爲它沒有公開暴露。 – Aybe