WPF Converterで色や表示状態を変える

Converterを使ってコントロールの色や表示状態を変えるサンプル。

// xaml
<Grid.Resources>
    <local:ColorToBrushConverter x:Key="ColorToBrushConverter" />
    <local:VisiblityConverter x:Key="VisiblityConverter" />
</Grid.Resources>

<Button Content="Button" Name="button1" Height="23" Width="75" 
        Visibility="{Binding VisiblityValue, Converter={StaticResource VisiblityConverter}}"
        Background="{Binding ColorValue, Converter={StaticResource ColorConverter}}" />

// cs
[System.Windows.Data.ValueConversion(typeof(int), typeof(System.Windows.Media.Color))]
public class ColorToBrushConverter : System.Windows.Data.IValueConverter   
{  
    #region IValueConverter メンバ   

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)   
    {
        int target = (int)value;

        if (target == 1)
            return new SolidColorBrush(System.Windows.Media.Colors.Aqua);

        else if (target == 2)
            return new SolidColorBrush(System.Windows.Media.Colors.Red);

        return new SolidColorBrush(System.Windows.Media.Colors.Gray);
    }

    // TwoWayの場合に使用する
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)   
    {   
        throw new NotImplementedException();
    }  

    #endregion
}

[System.Windows.Data.ValueConversion(typeof(int), typeof(System.Windows.Visibility))]
public class VisiblityConverter : System.Windows.Data.IValueConverter
{
    #region IValueConverter メンバ

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int state = (int)value;

        if (state == 0)
            return System.Windows.Visibility.Visible;

        return System.Windows.Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}