因爲您正在查找的值位於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應用程序事件和屬性。
我使用的是ListView而不是ListBox - 我還需要GetChildOfType方法嗎? –
恐怕是的,因爲這是你如何獲得內部ScrollViewer,因爲它沒有公開暴露。 – Aybe