Binding window's background
I want to bind the background of a window to some string property, such that I'll have a gradient background in different colors when the property changes:
<Window.Background>
<LinearGradientBrush>
<LinearGradientBrush.GradientStops>
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="{Binding Source={RelativeSource Mode=Self},
Path=backgroud_color}" Offset="1"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Window.Background>
code behind:
public event PropertyChangedEventHandler PropertyChanged;
private string _backgroud_color;
public string backgroud_color
{
get { return _backgroud_color; }
set
{
_backgroud_color = value;
OnPropertyChanged("backgroud_color");
}
}
public void OnPropertyChanged(string开发者_开发问答 property_name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property_name));
}
but the background does not change at all. What is the problem?
The problem is the RelativeSource in the Binding. It'll refer to the GradientStop which doesn't have a backgroud_color Property. Have you set the DataContext for the Window? In that case, you can just bind to backgroud_color like this
<Window.Background>
<LinearGradientBrush>
<LinearGradientBrush.GradientStops>
<GradientStop Color="White" Offset="0.5"/>
<GradientStop Color="{Binding Path=backgroud_color}" Offset="1" />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Window.Background>
Code behind
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
You can go through the following link......might find it good to learn and understand basics.....
精彩评论