lundi 29 juillet 2019

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

I'm trying to make a CheckBox that looks like a little LED light: brightly colored when checked, gray when unchecked. In my app I need such status lights with different LED colors. I'm told the "WPF Way" is to find the control that works almost exactly like what you want, then customize it, so that's what I'm trying.

I found code for a ColorToSolidColorBrushValueConverter which will allow me to convert the CheckBox's Foreground color to a Brush to be used when filling the LED.

I honestly think the only thing I need to do now is complete the binding Path on the Ellipse's Fill property, but I haven't been able to determine the proper binding string. I've tried things like Path=Foreground, Path=Target.Foreground, Path=TargetSource.Foreground, Path=Source.Foreground, Path=Parent.Foreground--but nothing ever causes the Ellipse to show a fill color.

In my code I commented out a trigger set up to change the color when the box is unchecked, so I could be sure the trigger wasn't behaving unexpectedly and preventing me from seeing the color. I deleted the commented-out code for brevity in this post, so that's why this style as shown can currently only display the "checked" state.

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


I expect the Ellipse named ColorDot to be filled in with some color at some point, but it's always blank, I think because I haven't determined the correct Path for the Fill Binding.




Aucun commentaire:

Enregistrer un commentaire