c# - 从 C# 访问 ListBox 的 ScrollViewer

标签 c# wpf xaml listbox scrollviewer

我想从 C# 更改 ListBoxScrollViewer 的属性。

我找到了 this question在 Stackoverflow 上。我采纳了接受的答案的建议,并将 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”按钮时,它会打印“null”。即,未检索到 ScrollViewer

我如何到达该死的 ScrollViewer? :-)

最佳答案

你可以试试这个小辅助函数

用法

var scrollViewer = GetDescendantByType(yourListBox, typeof(ScrollViewer)) as ScrollViewer;

辅助函数

public static Visual GetDescendantByType(Visual element, Type type)
{
  if (element == null) {
    return null;
  }
  if (element.GetType() == type) {
    return element;
  }
  Visual foundElement = null;
  if (element is FrameworkElement) {
    (element as FrameworkElement).ApplyTemplate();
  }
  for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) {
    Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
    foundElement = GetDescendantByType(visual, type);
    if (foundElement != null) {
      break;
    }
  }
  return foundElement;
}

希望对你有帮助

关于c# - 从 C# 访问 ListBox 的 ScrollViewer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10293236/

相关文章:

c# - 创建自定义异常还是使用内置异常?

C# WPF Window.ShowDialog 堆栈溢出异常

c# - 为什么新的.Net 4.0 EF应用程序会随机锁定?

c# - 更改网格中行的背景颜色

c# - 为什么 Color.A = 255 on Color 不会使其完全不透明?

c# - JQuery 不能在带有 Masterpage 的 aspx-page 中工作

WPF数据绑定(bind)计时问题

c# - Kinect手势分析

wpf - 将一个项目拆分为两个独立的MVVM子项目是否正确

c# - WPF 多复选框选中/取消选中