以编程方式更改WPF可编辑ComboBox的背景颜色

时间:2016-03-23 12:00:35

标签: c# wpf combobox

我尝试使用代码在运行时动态更改可编辑ComboBox的背景颜色。特别是,我想更改TextBox中可编辑ComboBox的背景。

在SO上有几个答案,就像这个:

WPF change the background color of an edittable combobox in code

然而,问题在于它们全部基于XAML并编辑默认模板。我不想这样做,我正在寻找一种只使用代码的通用解决方案。

有可能吗?我尝试了一个看似显而易见的解决方案:

TextBox textBox = (TextBox)comboBox.Template.FindName("PART_EditableTextBox", comboBox);
textBox.Background = Brushes.Yellow;

但这绝对没有。我错过了什么?

2 个答案:

答案 0 :(得分:2)

这就是你如何做到的

<ComboBox Loaded="MyCombo_OnLoaded"  x:Name="myCombo" IsEditable="True"></ComboBox>

private void MyCombo_OnLoaded(object sender, RoutedEventArgs e)
{
      var textbox = (TextBox)myCombo.Template.FindName("PART_EditableTextBox", myCombo);
      if (textbox!= null)
      {
           var parent = (Border)textbox.Parent;
           parent.Background = Brushes.Yellow;
       }
}

答案 1 :(得分:2)

仅适用于xaml粉丝的可重用AttachedProperty解决方案:

<ComboBox Background="Orange" IsEditable="True" Text="hi" local:ComboBoxHelper.EditBackground="Red"></ComboBox>

实现:

public static class ComboBoxHelper
{
    public static readonly DependencyProperty EditBackgroundProperty = DependencyProperty.RegisterAttached(
        "EditBackground", typeof (Brush), typeof (ComboBoxHelper), new PropertyMetadata(default(Brush), EditBackgroundChanged));

    private static void EditBackgroundChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
    {
        var combo = dependencyObject as ComboBox;
        if (combo != null)
        {
            if (!combo.IsLoaded)
            {
                RoutedEventHandler comboOnLoaded = null;
                comboOnLoaded = delegate(object sender, RoutedEventArgs eventArgs)
                {
                    EditBackgroundChanged(dependencyObject, args);
                    combo.Loaded -= comboOnLoaded;
                };
                combo.Loaded += comboOnLoaded;

                return;
            }

            var part = combo.Template.FindName("PART_EditableTextBox", combo);
            var tb = part as TextBox;
            if (tb != null)
            {
                var parent = tb.Parent as Border;
                if (parent != null)
                {
                    parent.Background = (Brush)args.NewValue;
                }
            }
        }
    }

    [AttachedPropertyBrowsableForType(typeof(ComboBox))]
    public static void SetEditBackground(DependencyObject element, Brush value)
    {
        element.SetValue(EditBackgroundProperty, value);
    }

    [AttachedPropertyBrowsableForType(typeof(ComboBox))]
    public static Brush GetEditBackground(DependencyObject element)
    {
        return (Brush) element.GetValue(EditBackgroundProperty);
    }
}