patrick
patrick

Reputation: 16979

How can I get access to the ScrollViewer inside a ComboBox in WPF?

The ComboBox Control Template has a ScrollViewer. How can I get a reference to it from an instance of a ComboBox?

I tried naming it "ScrollViwer1" and using this, but I had no success.

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

Upvotes: 2

Views: 2379

Answers (1)

kmatyaszek
kmatyaszek

Reputation: 19296

You can use FrameworkTemplate.FindName Method.

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

Upvotes: 4

Related Questions