訪問列表框的ScrollViewer中我想的ScrollViewer
一個ListBox
的性質從C#改變。從C#
我發現這裏this question#2。我接受了接受答案的建議,並將ScrollViewer
作爲子類的屬性公開。但是,這在下面顯示的示例中似乎不起作用。該問題中的一些評論也表明這種技術無效。
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
。
我如何去織補ScrollViewer
? :-)
檢查也是這個 http://stackoverflow.com/questions/3963341/get-reference-to-my-wpf-listboxs-scrollviewer-in-c – Klaus78 2012-04-24 07:22:45
...你真的不應該調用你的ScrollViewer屬性「ScrollViewer」。 – basti 2012-04-24 07:55:29
@chiffre:爲什麼不呢?它實際上是在.NET的命名指南中的屬性:**考慮賦予一個屬性與其類型相同的名稱**(http://msdn.microsoft.com/zh-cn/library/ms229012。aspx) – 2012-04-24 08:24:19