首页 > 解决方案 > 根据选择的值更改为 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#pythonwpf

解决方案


我看到你已经包含了一个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;指令,这应该像一个魅力。


推荐阅读