自定义绘制复选框时,如何将椭圆形的填充颜色绑定到复选框的前景?

When custom drawing a Checkbox, how can I bind my Ellipse Shape's Fill color to the CheckBox's Foreground?

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

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

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

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

          <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 会在某个时候填充一些颜色,但它总是空白,我想是因为我还没有确定 Fill Binding 的正确路径。

Fill="{TemplateBinding Background}"

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

中设置的

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