How can I bind a background color in WPF/XAML?

后端 未结 8 1797
情话喂你
情话喂你 2020-12-05 04:01

What do I have to change to the following code so that the background is red, neither of the 2 ways I tried worked:


(source: deviantsart.com)

8条回答
  •  旧巷少年郎
    2020-12-05 04:40

    You assigned a string "Red". Your Background property should be of type Color:

    using System.Windows;
    using System.ComponentModel;
    
    namespace TestBackground88238
    {
        public partial class Window1 : Window, INotifyPropertyChanged
        {
    
            #region ViewModelProperty: Background
            private Color _background;
            public Color Background
            {
                get
                {
                    return _background;
                }
    
                set
                {
                    _background = value;
                    OnPropertyChanged("Background");
                }
            }
            #endregion
    
            //...//
    }
    

    Then you can use the binding to the SolidColorBrush like this:

    public Window1()
    {
        InitializeComponent();
        DataContext = this;
    
        Background = Colors.Red;
        Message = "This is the title, the background should be " + Background.toString() + ".";
    
    }
    

    not 100% sure about the .toString() method on Color-Object. It might tell you it is a Color-Class, but you will figur this out ;)

提交回复
热议问题