从 C# 访问 ListBox 的 ScrollViewer [英] Accessing the ScrollViewer of a ListBox from C#
问题描述
我想更改 C# 中 ListBox
的 ScrollViewer
的属性.
I'd like to change the properties of a ScrollViewer
of a ListBox
from C#.
我找到了 this question 在 Stackoverflow 上.我接受了接受的答案的建议,并将 ScrollViewer
作为子类的属性公开.但是,这在下面显示的示例中似乎不起作用.该问题中的一些评论也指出这种技术不起作用.
I found this question here on Stackoverflow. I took the accepted answer's advice and exposed the ScrollViewer
as a property of a subclass. However, this doesn't appear to be working in an example shown below. Some of the comments in that question also state that this technique didn't work.
XAML:
<Window x:Class="StackoverflowListBoxScrollViewer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
</Window>
C#:
using System;
using System.Windows;
using System.Windows.Controls;
namespace StackoverflowListBoxScrollViewer
{
public class MyListBox : ListBox
{
public ScrollViewer ScrollViewer
{ get { return (ScrollViewer)GetTemplateChild("ScrollViewer"); } }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var myListBox = new MyListBox();
Content = myListBox;
myListBox.Items.Add(new Button() { Content = "abc" });
myListBox.Items.Add(new Button() { Content = "abc" });
myListBox.Items.Add(new Button() { Content = "abc" });
myListBox.Items.Add(new Button() { Content = "abc" });
myListBox.Items.Add(new Button() { Content = "abc" });
var button = new Button() { Content = "Check ScrollViewer" };
button.Click += (s, e) =>
{
if (myListBox.ScrollViewer == null)
Console.WriteLine("null");
};
myListBox.Items.Add(button);
}
}
}
当我点击Check ScrollViewer"按钮时,它会打印null".即,未检索到 ScrollViewer
.
When I click the "Check ScrollViewer" button, it prints "null". I.e., the ScrollViewer
wasn't retrieved.
我怎么去那个该死的ScrollViewer
?:-)
How do I get to that darn ScrollViewer
? :-)
推荐答案
如果您将使用标准 ListBox,那么您可以将您的 getter 更改为这个:
If you will use standard ListBox, so you can change yours getter to this one:
public class MyListBox : ListBox
{
public ScrollViewer ScrollViewer
{
get
{
Border border = (Border)VisualTreeHelper.GetChild(this, 0);
return (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
}
}
}
这篇关于从 C# 访问 ListBox 的 ScrollViewer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!