Accès au ScrollViewer d'un ListBox à partir de C #

Je voudrais changer les propriétés d'un ScrollViewer d'un ListBox à partir de C#.

J'ai trouvé cette question ici sur Stackoverflow. J'ai pris la accepté de répondre à des conseils et de l'exposé de la ScrollViewer en tant que propriété d'une sous-classe. Toutefois, cela ne semble pas être à travailler dans l'exemple illustré ci-dessous. Certains commentaires que la question aussi de l'état que cette technique ne fonctionne pas.

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);
        }
    }
}

Lorsque je clique sur "Check " ScrollViewer" bouton, il affiche "null". I. e., le ScrollViewer n'était pas récupérés.

Comment puis-je obtenir ce fameux ScrollViewer? 🙂

source d'informationauteur dharmatech