Changing to background/text color of a ComboBox depending on the value chosen

时间:2018-07-24 10:13:49

标签: c# python wpf

I would like to be able to change the background color of a combo box depending on the value chosen in a wpf.

I have tried using python to do this but I am new to programming (and IT in general)

Could you point me in the right direction, please?

Current code:

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

1 个答案:

答案 0 :(得分:0)

我看到您已经包含一个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;伪指令,并且该伪指令应该像魅力一样工作。

相关问题