首页 > 解决方案 > 自定义绘制复选框时,如何将椭圆形的填充颜色绑定到复选框的前景?

问题描述

我正在尝试制作一个看起来像一个小 LED 灯的 CheckBox:选中时颜色鲜艳,未选中时为灰色。在我的应用程序中,我需要具有不同 LED 颜色的状态灯。有人告诉我“WPF 方式”是找到几乎与您想要的完全一样的控件,然后对其进行自定义,这就是我正在尝试的。

我找到了 ColorToSolidColorBrushValueConverter 的代码,它允许我将 CheckBox 的前景色转换为在填充 LED 时使用的画笔。

老实说,我现在唯一需要做的就是完成 Ellipse 的 Fill 属性上的绑定路径,但我无法确定正确的绑定字符串。我尝试过诸如 Path=Foreground、Path=Target.Foreground、Path=TargetSource.Foreground、Path=Source.Foreground、Path=Parent.Foreground 之类的东西——但没有任何东西会导致 Ellipse 显示填充颜色。

在我的代码中,我注释掉了一个触发器,该触发器设置为在未选中该框时更改颜色,因此我可以确定触发器没有出现意外行为并阻止我看到颜色。为了简洁起见,我删除了这篇文章中注释掉的代码,这就是为什么所示的这种样式目前只能显示“已检查”状态的原因。

          <converters:ColorToSolidColorBrushValueConverter x:Key="ColorToBrush" />

          <Style x:Key="StyleDotCheckBox" TargetType="{x:Type CheckBox}">
            <Setter Property="Template">
              <Setter.Value>
                <ControlTemplate TargetType="{x:Type CheckBox}">
                  <StackPanel Orientation="Horizontal">
                    <Ellipse x:Name="ColorDot"
                             HorizontalAlignment="Center"
                             Stretch="UniformToFill"
                             StrokeLineJoin="Round"
                             Stroke="Black"
                             Fill="{Binding Path=Foreground, Converter={StaticResource ColorToBrush}}"
                             Margin="1"
                             />
                  </StackPanel>
                </ControlTemplate>
              </Setter.Value>
            </Setter>
          </Style>

我希望名为 ColorDot 的 Ellipse 会在某个时候用某种颜色填充,但它始终是空白的,我想是因为我还没有确定填充绑定的正确路径。

标签: wpfcheckboxbindingproperty-binding

解决方案


Fill="{TemplateBinding Background}"

是您所需要的,因为您是从ControlTemplate.

不需要转换器,因为Background它已经是一个Brush对象。


推荐阅读