Search code examples
wpfblend

How can i change the backround color of a rectange by clicking on a checkbox


Im Using Blend and have the following Problem:

How can i Change the Background Color of a rectangle by clicking on a checkbox? When i go via right click, edit template and then edit a copy i can only edit the current object. In this cas it would be the checkbox. But i want to use the checkbox to edit the style of a rectange object. Is this possible?


Solution

  • you can bind to the IsChecked property and use a ValueConverter

    <CheckBox x:Name="cb" />
    <Rectangle Fill="{Binding ElementName=cb, Path=IsChecked, Mode=OneWay, Converter={StaticResource CheckedToBackgroundConverter}}" />
    

    the value converter

    public class CheckedToBackgroundConverter: IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
        return value is bool && (bool)value ? Brushes.Blue : Brushes.Red;
      }
    
      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
        return DependencyProperty.UnsetValue;
      }
    }
    

    hope that helps