Silverlight data affecting look .. VisualStateManger .. color according to data value
In Silverlight how do I get the color of a button to change according to the value of it开发者_开发知识库s contents .. e.g. '0' = red , '1' = green ..
I have taken a look at the VisualStateManger but cannot see how to do it .. I can see it is easy for mouseovers etc .. but not for values of data.
What you need is a value converter, that is an implementation of IValueConverter
. In this blog article you find the code for a StringToObjectConverter
which you can use for your task. I'll reproduce the code here:-
using System;
using System.Windows;
using System.Windows.Data;
using System.Linq;
using System.Windows.Markup;
namespace SilverlightApplication1
{
[ContentProperty("Items")]
public class StringToObjectConverter : IValueConverter
{
public ResourceDictionary Items { get; set; }
public string DefaultKey { get; set; }
public StringToObjectConverter()
{
DefaultKey = "__default__";
}
public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && Items.Contains(value.ToString()))
return Items[value.ToString()];
else
return Items[DefaultKey];
}
public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Items.FirstOrDefault(kvp => value.Equals(kvp.Value)).Key;
}
}
}
Now you can add an instance of this converter to the resources in you your user control:-
<UserControl.Resources>
<local:StringToObjectConverter x:Key="StatusToBrush">
<ResourceDictionary>
<SolidColorBrush Color="Red" x:Key="0" />
<SolidColorBrush Color="Green" x:Key="1" />
<SolidColorBrush Color="Silver" x:Key="__default__" />
</ResourceDictionary>
</local:StringToObjectConverter>
</UserControl>
Now you can bind the Background
to your value:-
<Button Background="{Binding Value, Converter={StaticResource StatusToBrush}}">
<TextBlock Text="{Binding Value}" />
</Button>
精彩评论