c# - 根据选择的值更改为 ComboBox 的背景/文本颜色
问题描述
我希望能够根据 wpf 中选择的值更改组合框的背景颜色。
我曾尝试使用 python 来做到这一点,但我是编程新手(通常是 IT)
请给我指出正确的方向好吗?
当前代码:
from System import Decimal
from System.Windows import MessageBox
from System.Windows import LogicalTreeHelper
from System.Windows.Input import KeyEventHandler
from System.Windows.Media import Brush, Brushes, ColorConverter
import sys
from time import sleep
class PythonDemo(object):
def Init(self,_tikitDbAccess,_tikitSender):
self._tikitDbAccess=_tikitDbAccess
self._tikitSender=_tikitSender
self.combobox=LogicalTreeHelper.FindLogicalNode(self._tikitSender, 'ComboBox1')
self.combobox.LostFocus += self.ColorChange
def ColorChange(self,sender,e):
#List of things i have tried
self.combobox.Background.Color="Red"# also tried "#FF00FF00"
self.combobox.Background="Red"
self.combobox.SelectedItem.Background="Red"
oPythonDemo=PythonDemo
解决方案
我看到你已经包含了一个C#
标签,所以我会给你一个 C# 的解决方案。如果您需要 Python 中的解决方案,我无法帮助您,但是您听起来好像您不在乎,所以这是我的最大努力。
我不知道你的 XAML 是什么样子的,所以我只能给你一个粗略的实现,但你应该能够轻松实现。
这是 XAML:
<Grid>
<ComboBox Name="ComboBox1" SelectionChanged="ComboBox1_SelectionChanged" Height="50" Width="Auto">
<ComboBoxItem Name="GreenOption" Content="Green"/>
<ComboBoxItem Name="BlueOption" Content="Blue"/>
<ComboBoxItem Name="PinkOption" Content="Pink"/>
<ComboBoxItem Name="RedOption" Content="Red"/>
</ComboBox>
</Grid>
同样,应该用你碰巧拥有的任何东西来代替,这只是一个例子。这是C#:
using System.Windows.Media;
/*The rest of your code goes here*/
private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var foo = sender as ComboBox;
var bar = foo.SelectedItem as ComboBoxItem;
switch (bar.Name)
{
case "GreenOption":
foo.Background = Brushes.Green;
break;
case "PinkOption":
foo.Background = Brushes.Pink;
break;
case "RedOption":
foo.Background = Brushes.Red;
break;
case "BlueOption":
foo.Background = Brushes.Blue;
break;
}
}
/* Or Here */
很有可能还有更优雅的解决方案,我不知道在Python中会怎么做,但基本原理应该是一样的。确保你记住了using System.Windows.Media;
指令,这应该像一个魅力。
推荐阅读
- c# - C# - 随机化四个字符串大小写的函数总是在相同的情况下返回每个字符串
- php - 当我运行控制 exe 时,Xampp 带来了 apache 和 mysql
- r - 如何将函数的打印输出存储为R中的向量?
- swift - 当您不知道使用什么值进行初始化时进行 Swift 初始化
- c# - 配置 Visual Studio 自动完成以列出命名空间之外的类?
- python - 为特定用户保存 .docx 文件 django
- python - 在 C++ 中,为什么某些参数需要 &?
- python - numpy arange 函数构建数组大小错误
- f# - 如何在 F# 中制作 uint32?
- ruby - Bundler 找不到 gem "bundle" 的兼容版本,但 gem 列表没有它说安装的版本