2010-12-06 6 views

答えて

0

価値コンバータは、IValueConverterの実装です。このblog articleには、自分の仕事に使用できるStringToObjectConverterのコードがあります。私はここのコードを再現します: -

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; 
     } 
    } 
} 

今、あなたのユーザーコントロールあなたのリソースにこのコンバーターのインスタンスを追加することができます -

<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> 

今、あなたはあなたにBackgroundをバインドすることができます値: -

<Button Background="{Binding Value, Converter={StaticResource StatusToBrush}}"> 
    <TextBlock Text="{Binding Value}" /> 
</Button> 
関連する問題