从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#.
我找到了这个问题在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);
}
}
}
当我单击检查ScrollViewer"按钮时,它会显示空".也就是说,未检索到ScrollViewer
.
When I click the "Check ScrollViewer" button, it prints "null". I.e., the ScrollViewer
wasn't retrieved.
我该如何达到该目标? :-)
How do I get to that darn ScrollViewer
? :-)
推荐答案
如果您将使用标准ListBox,则可以将自己的吸气剂更改为此:
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屋!