如何通过单击复选框更改矩形的背景颜色

时间:2013-07-29 08:19:19

标签: wpf blend

我正在使用Blend并遇到以下问题:

如何通过单击复选框更改矩形的背景颜色?当我通过右键单击,编辑模板,然后编辑副本,我只能编辑当前对象。在这个cas中它将是复选框。但我想使用复选框来编辑rectange对象的样式。这可能吗?

1 个答案:

答案 0 :(得分:0)

您可以绑定到IsChecked属性并使用ValueConverter

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

值转换器

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

希望有所帮助