How can I bind a background color in WPF/XAML?
Solution 1
Important:
Make sure you're using System.Windows.Media.Brush
and not System.Drawing.Brush
They're not compatible and you'll get binding errors.
The color enumeration you need to use is also different
System.Windows.Media.Colors.Aquamarine (class name isColors
) <--- use this one System.Drawing.Color.Aquamarine (class name isColor
)
If in doubt use Snoop
and inspect the element's background property to look for binding errors - or just look in your debug log.
Solution 2
The Background
property expects a Brush
object, not a string. Change the type of the property to Brush
and initialize it thus:
Background = new SolidColorBrush(Colors.Red);
Solution 3
Here you've got a copy-paste code:
class NameToBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value.ToString() == "System")
{
return new SolidColorBrush(System.Windows.Media.Colors.Aqua);
}else
{
return new SolidColorBrush(System.Windows.Media.Colors.Blue);
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
Solution 4
I figured this out, it was just a naming conflict issue: if you use TheBackground instead of Background it works as posted in the first example. The property Background was interfering with the Window property background.
Solution 5
I recommend reading the following blog post about debugging data binding: http://beacosta.com/blog/?p=52
And for this concrete issue: If you look at the compiler warnings, you will notice that you property has been hiding the Window.Background property (or Control or whatever class the property defines).
Angry Dan
web/software developer, .NET, C#, WPF, PHP, software trainer, English teacher, have philosophy degree, love languages, run marathons my tweets: http://www.twitter.com/edward_tanguay my runs: http://www.tanguay.info/run my code: http://www.tanguay.info/web my publications: PHP 5.3 training video (8 hours, video2brain) my projects: http://www.tanguay.info
Updated on August 20, 2020Comments
-
Angry Dan over 3 years
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)XAML:
<Window x:Class="TestBackground88238.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <StackPanel> <TextBlock Text="{Binding Message}" Background="{Binding Background}"/> <TextBlock Text="{Binding Message}"> <TextBlock.Background> <SolidColorBrush Color="{Binding Background}"/> </TextBlock.Background> </TextBlock> </StackPanel> </Window>
Code Behind:
using System.Windows; using System.ComponentModel; namespace TestBackground88238 { public partial class Window1 : Window, INotifyPropertyChanged { #region ViewModelProperty: Background private string _background; public string Background { get { return _background; } set { _background = value; OnPropertyChanged("Background"); } } #endregion #region ViewModelProperty: Message private string _message; public string Message { get { return _message; } set { _message = value; OnPropertyChanged("Message"); } } #endregion public Window1() { InitializeComponent(); DataContext = this; Background = "Red"; Message = "This is the title, the background should be " + Background + "."; } #region INotifiedProperty Block public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } }
Update 1:
I tried Aviad's answer which didn't seem to work. I can do this manually with x:Name as shown here but I want to be able to bind the color to a INotifyPropertyChanged property, how can I do this?
(source: deviantsart.com)XAML:
<Window x:Class="TestBackground88238.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <StackPanel> <TextBlock Text="{Binding Message}" Background="{Binding Background}"/> <TextBlock x:Name="Message2" Text="This one is manually orange."/> </StackPanel> </Window>
Code Behind:
using System.Windows; using System.ComponentModel; using System.Windows.Media; namespace TestBackground88238 { public partial class Window1 : Window, INotifyPropertyChanged { #region ViewModelProperty: Background private Brush _background; public Brush Background { get { return _background; } set { _background = value; OnPropertyChanged("Background"); } } #endregion #region ViewModelProperty: Message private string _message; public string Message { get { return _message; } set { _message = value; OnPropertyChanged("Message"); } } #endregion public Window1() { InitializeComponent(); DataContext = this; Background = new SolidColorBrush(Colors.Red); Message = "This is the title, the background should be " + Background + "."; Message2.Background = new SolidColorBrush(Colors.Orange); } #region INotifiedProperty Block public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } }
-
Angry Dan over 14 yearsthat didn't seem to work for me, I posted the code above (update 1)
-
Angry Dan over 14 yearsyes, the compiler warning was how I discovered it, thanks for the link, good information there
-
aruno over 11 yearsbe sure to use SolidColorBrush from System.Windows.Media and not SolidBrush from System.Drawing
-
DanteTheEgregore almost 11 yearsI know I'm a bit late to the party but it's Colors.Red, not Color.Red. Was a bit confused by your answer till I found that one out.
-
frostymarvelous about 10 yearsChanging from using raw colors to using SolidColorBrush solved it for me. thanks
-
Martas over 6 yearsThe simplest variant in such case is to use predefined solid color brushes Background = Brushes.Red //System.Windows.Media
-
Martas over 6 yearsThe simplest variant in such case is to use predefined solid color brushes Background = Brushes.Red //System.Windows.Media
-
Ouissal about 5 yearsUnfortunately that link no longer works, do you know about a similar post? Thanks
-
John Doe over 4 yearsPlease note that
System.Windows.Media.Colors
namespace returns aSystem.Windows.Media.Color
with nos
. -
John Doe over 4 yearsA frustrating and easily missed concept:
<TextBlock Background="{Binding TheBackground}"/>
was asked and needs theSystem.Windows.Media.SolidColorBrush
namespace. If you need opacity and so use <TextBlock><TextBlock.Background><SolidColorBrush Color="{Binding TheBackground}"
Opacity="{Binding TheOpacity}"/></TextBlock.Background></TextBlock>, you needSystem.Windows.Media.Color
namespace. This answer shows how to convert between the two. -
david2020 over 3 years"Make sure you're using System.Windows.Media.Brush and not System.Drawing.Brush" this phrase helped
-
Faither over 3 years