WPF 如何使用 C# 调用嵌入在组合框控件中的切换按钮

本文关键字:控件 按钮 组合 何使用 调用 WPF | 更新日期: 2023-09-27 18:37:23

所以我遇到的问题是我想访问ComboBox的切换按钮,特别是切换按钮的"点击"事件,但我找不到访问切换按钮的好方法,因为它嵌入到ComboBox的控件模板中。

我知道您可以通过在 XAML 中创建自己的控件模板来实现它,但我不想只为一个微小的更改为 ComboBox 创建一个全新的控件模板。

有没有办法通过 C# 访问切换按钮?

这是我的结构供参考:可视化树结构
(抱歉,没有足够的点来嵌入图像)

使用以下命令可以轻松获取组合框的弹出窗口/文本框控件:

comboBox.Template.FindName("PART_Popup", combobox) comboBox.Template.FindName("PART_EditableTextBox", comboBox)

但是ComboBox的切换按钮没有一个名字可以调用它。

WPF 如何使用 C# 调用嵌入在组合框控件中的切换按钮

你可以这样做:

var tgs = FindVisualChild<ToggleButton>(comboBox);
if (tgs != null && tgs.Count > 0)
{
    tgs[0].Width = 20;
}

FindVisualChild 函数:

public static List<T> FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        List<T> childItems = null;
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            if (childItems == null)
                childItems = new List<T>();
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                childItems.Add((T)child);
            }
            var recursiveChildItems = FindVisualChild<T>(child);
            if (recursiveChildItems != null && recursiveChildItems.Count > 0)
                childItems.AddRange(recursiveChildItems);
        }
        return childItems;
    }
    return null;
}