以编程方式更改WPF可编辑ComboBox的背景颜色 [英] Change the background color of a WPF editable ComboBox programmatically

查看:1074
本文介绍了以编程方式更改WPF可编辑ComboBox的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在运行时使用代码动态更改可编辑的 ComboBox 的背景颜色。特别是,我想更改可编辑 TextBox 的背景,该文本框是 ComboBox 的一部分。

I'm trying to dynamically change the background color of an editable ComboBox at runtime, using code. In particular, I want to change the background of the editable TextBox that is part of the ComboBox.

关于SO的答案有几个,就像这样:

There are several answers about this on SO, like this one:

WPF在代码中更改可编辑组合框的背景颜色

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

however, the problem is that they're all based on XAML and editing default templates. I don't want to do that, I'm searching for a generic solution that works with just code.

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

Is it possible? I tried the solution that seems obvious:

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

但这绝对没有作用。我缺少什么?

But this does absolutely nothing. What am I missing?

推荐答案

这是您可以做到的方式

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

这篇关于以编程方式更改WPF可编辑ComboBox的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆