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)
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 ;)
You can still use "Background" as the property name, as long as you give your window a name and use this name on the "Source" of the Binding.
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);
The xaml code:
<Grid x:Name="Message2">
<TextBlock Text="This one is manually orange."/>
</Grid>
The c# code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
CreateNewColorBrush();
}
private void CreateNewColorBrush()
{
SolidColorBrush my_brush = new SolidColorBrush(Color.FromArgb(255, 255, 215, 0));
Message2.Background = my_brush;
}
This one works in windows 8 store app. Try and see. Good luck !
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).
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.