【问题标题】:how to change background color using dependency property如何使用依赖属性更改背景颜色
【发布时间】:2017-11-01 10:29:58
【问题描述】:

我是 wpf 的新手,我正在尝试学习依赖属性。 我试图使用来自另一个文本框的文本来更改文本框的背景颜色。我可以使用转换器来做到这一点,但我想使用依赖属性来实现它。 这是xaml代码

<TextBox Name="setbox" Width="150" Height="50" FontWeight="DemiBold" FontSize="25" Canvas.Top="50" Canvas.Left="10"
                Background="{Binding ElementName=statusbar,Path=Text,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource converter1}}"/>

这是我的转换器代码

public class backgroundColourConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo
         culture)
        {
            var backColor = Brushes.Transparent;
            //changes the colour of font to White if the input to the statusbar is "state1"
            if (value != null && value.ToString().Equals("state1"))
            {
                backColor = Brushes.White;
            }
            //changes the colour of font to Lavender if the input to the statusbar is "state2"
            else if (value != null && value.ToString().Equals("state2"))
            {
                backColor = Brushes.Lavender;
            }
            //changes the colour of font to Ivory if the input to the statusbar is "state3"
            else if (value != null && value.ToString().Equals("state3"))
            {
                backColor = Brushes.Ivory;
            }
            //changes the colour of font to Green if the input to the statusbar is "state4"
            else if (value != null && value.ToString().Equals("state4"))
            {
                backColor = Brushes.Green;
            }
            return backColor;
        }



        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

这工作正常,但我想使用dependecy 属性来实现它。 提前致谢

【问题讨论】:

标签: c# wpf dependency-properties ivalueconverter


【解决方案1】:

如果您创建自己的 TextBox 控件,则可以添加一个新属性 BackgroundColorText 并从您在其中键入颜色名称的其他 TextBox 设置其值。在 BackgroundColorText 的设置器中,您可以设置控件的背景颜色。

但这对于仅仅修改背景颜色来说有点矫枉过正。正确的做法是值转换器,恕我直言。

【讨论】:

    猜你喜欢
    • 2012-12-07
    • 1970-01-01
    • 2012-07-05
    • 2014-11-21
    • 2021-06-07
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多