i need to change the background of labels and buttons when a boolean variable is true (back to default color on false). so i wrote an attached property. it looks like this so far:
public class BackgroundChanger : DependencyObject
{
#region dependency properties
// status
public static bool GetStatus(DependencyObject obj)
{
return (bool)obj.GetValue(StatusProperty);
}
public static void SetStatus(DependencyObject obj, bool value)
{
obj.SetValue(StatusProperty, value);
}
public static readonly DependencyProperty StatusProperty = DependencyProperty.RegisterAttached("Status",
typeof(bool), typeof(BackgroundChanger), new UIPropertyMetadata(false, OnStatusChange));
#endregion
private static void OnStatusChange(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var element = obj as Control;
if (element != null)
{
if ((bool)e.NewValue)
element.Background = Brushes.LimeGreen;
else
element.Background = default(Brush);
}
}
}
and i use it like this:
<Label CustomControls:BackgroundChanger.Status="{Binding test}" />
it works fine. when the according variable test is set in the viewmodel, the backgroundcolor changes to LimeGreen.
my question:
the color LimeGreen is hard coded. i would like to set that color (and the default color as well) in the XAML as well. so i can decide between which two colors the background switches. how can i do that?
You can have multiple attached properties. Accessing them is easy, there are static
Get..andSet..methods, to which you supplyDependencyObjectwhich attached property value you want to operate.In xaml it will look like