从数据库(WPF)更改BackGround颜色?

时间:2014-05-18 23:59:59

标签: c# wpf data-binding background inotifypropertychanged

感谢您花时间看看我的问题,我查看了几个问题并且没有找到任何相关信息,所以这就是我想要做的事情:

1 - 我希望有一个像:Colors_Table这样的表格,然后保存所有的Hex颜色。

2-设置将用于我的客户端的十六进制颜色,如Properties_Table,然后有一行MainBackGroundColor,这就是我将用于背景的颜色。

我不知道自己是否清楚,基本上我想要的是能够从数据库中设置背景颜色。

1 个答案:

答案 0 :(得分:2)

你的问题很清楚。为此,您可以像这样向窗口添加背景属性...

<Window.Background>
    <SolidColorBrush Color="{Binding MyBackgroundColor}"/>
</Window.Background>

请注意,画笔的颜色与属性绑定,而不是具有硬编码值。

然后在您的代码隐藏中,您可以使用此...

public partial class Window1 : Window, INotifyPropertyChanged
{
    public Window1()
    {
        InitializeComponent();
        DataContext = this;
        // set color here
        MyBackgroundColor = Colors.Red;
    }
    private Color _myBackgroundColor;
    public Color MyBackgroundColor
    {
        [DebuggerStepThrough]
        get { return _myBackgroundColor; }
        [DebuggerStepThrough]
        set
        {
            if (value != _myBackgroundColor)
            {
                _myBackgroundColor = value;
                OnPropertyChanged("MyBackgroundColor");
            }
        }
    }
    #region INotifyPropertyChanged Implementation
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string name)
    {
        var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}

在此示例中,背景为红色。如果您有十六进制格式的字符串,例如“#ffaabbcc”,则可以使用此转换...

        MyBackgroundColor =(Color) new ColorConverter().ConvertFrom(null, null, "#ffaabbcc");

...并获得您正在寻找的结果。

注意:

  • '#'应该是字符串的第一个字符。

    前两个字节是alpha通道