【问题标题】:how to change combo box background color in WPF?如何更改 WPF 中的组合框背景颜色?
【发布时间】:2022-01-21 22:59:19
【问题描述】:

我有一个 WPF 项目,我想动态设置它的背景颜色,这是我的 XAML 代码

<Window.Resources>
        <SolidColorBrush x:Key="TextBoxBorderColor" Color="#FFB4A5B4"/>
        <SolidColorBrush x:Key="TextBoxForegroundColor" Color="Black"/>
        <SolidColorBrush x:Key="TextBoxBackgroundColor" Color="White"/>
</Window.Resources>
<ComboBox x:Name="cmbUserFullName" Background="{DynamicResource TextBoxBackgroundColor}" Foreground="{DynamicResource TextBoxForegroundColor}" 
                          BorderBrush="{DynamicResource TextBoxBorderColor}">
</ComboBox>

这是我的代码


 var brush7 = FindResource("TextBoxBackgroundColor") as SolidColorBrush;
            if (!string.IsNullOrEmpty(Default.clrPckerTextBoxBackground)) brush7.Color = (Color)ColorConverter.ConvertFromString(Default.clrPckerTextBoxBackground);

            var brush8 = FindResource("TextBoxForegroundColor") as SolidColorBrush;
            if (!string.IsNullOrEmpty(Default.clrPckerTextBoxForeground)) brush8.Color = (Color)ColorConverter.ConvertFromString(Default.clrPckerTextBoxForeground);

            var brush9 = FindResource("TextBoxBorderColor") as SolidColorBrush;
            if (!string.IsNullOrEmpty(Default.clrPckerTextBoxBorder)) brush9.Color = (Color)ColorConverter.ConvertFromString(Default.clrPckerTextBoxBorder);

但它不会改变组合框背景颜色和边框画笔颜色。 谁能帮我知道我的代码哪里出了问题? 谢谢...

【问题讨论】:

  • 要添加或覆盖现有资源,您需要将值设置为资源本身,并插入从资源中获取的变量。在这种情况下, this.Resources["TextBoxBackgroundColor"] = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Default.clrPckerTextBoxBackground));
  • 我做了但是;它没有任何影响

标签: c# wpf combobox background


【解决方案1】:

尝试像这样删除并添加到当前资源中:

this.Resources.Remove("KeyName");
this.Resources.Add("KeyName", (Color)ColorConverter.ConvertFromString("ColorValue"));

理想情况下,您可以将您的画笔分组到不同的合并字典中(使用重复的键,但 SolidColorBrushes 的画笔值不同)并删除+将它们添加为一个组以一次性交换它们。

【讨论】:

  • 你能解释更多吗?
  • 试试这样的:- var brush7 = this.Resources["TextBoxBackgroundColor"] as SolidColorBrush; if (!string.IsNullOrEmpty(Default.clrPckerTextBoxBackground)) { this.Resources.Remove("TextBoxBackgroundColor"); this.Resources.Add("TextBoxBackgroundColor", (Color)ColorConverter.ConvertFromString(Default.clrPckerTextBoxBackground)); }
  • 不过你只有3把刷子,没关系。但是如果你想在更大的范围内进行,然后在不同的 Xamls 中添加画笔资源,并在应用程序级别而不是资源级别添加/删除合并字典,请查看此 StackOverflow Link
猜你喜欢
  • 2019-05-15
  • 2016-07-09
  • 2013-01-27
  • 2018-12-26
  • 2018-12-27
  • 2021-01-12
  • 2011-07-26
  • 1970-01-01
相关资源
最近更新 更多