如何在WPF中访问ComboBox中的ScrollViewer?

时间:2013-03-15 21:46:04

标签: wpf

ComboBox控件模板有一个ScrollViewer。如何从ComboBox的实例获取对它的引用?

我尝试将其命名为“ScrollViwer1”并使用此功能,但我没有成功。

var scroll = FindVisualChildByName<ScrollViewer>(this.comboBox, "ScrollViewer1");



  public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                string controlName = child.GetValue(Control.NameProperty) as string;
                if (controlName == name)
                {
                    return child as T;
                }
                else
                {
                    T result = FindVisualChildByName<T>(child, name);
                    if (result != null)
                        return result;
                }
            }
            return null;
        }

1 个答案:

答案 0 :(得分:4)

您可以使用FrameworkTemplate.FindName Method

ScrollViewer sv = comboBox.Template.FindName("DropDownScrollViewer", comboBox) as ScrollViewer;
if (sv != null)
{
    // do something...
}