WPF Custom Control Property Setter

custom-controlswpfxaml

I have a very simple Button-based control that displays an ellipse with color taken from custom dependency control called "Brush".

The template displays ellipse with proper color, but the Setters in Trigger do not recognize the "Brush" property (errors highlighted in the XAML file below).

How to access the "Brush" property in the setter so I can change its value on MouseOver?

XAML:

<Button x:Class="WpfTest.EllipseButton"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTest"
        Style="{DynamicResource localStyle}"
        Name="ellipseButton">

  <Button.Resources>
    <Style x:Key="localStyle"
           TargetType="local:EllipseButton">
      <Style.Setters>
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate>
              <Grid>
                <Ellipse Fill="{Binding ElementName=ellipseButton, Path=Brush}" />
              </Grid>
            </ControlTemplate>
          </Setter.Value>
        </Setter>
      </Style.Setters>
      <Style.Triggers>
        <Trigger Property="IsMouseOver"
                 Value="True">

          <!-- ERROR HERE: The property "Brush" is not a dependency property. -->
          <Setter Property="Brush"
                  Value="Blue" />
          <!-- ERROR HERE: The "BrushProperty" is not recognized or is not accessible.  -->
          <Setter Property="BrushPropety"
                  Value="Blue" />

        </Trigger>
      </Style.Triggers>
    </Style>
  </Button.Resources>
  <Grid>
  </Grid>
</Button>

code-behind:

public partial class EllipseButton : Button
{
    public static readonly DependencyProperty BrushProperty = DependencyProperty.Register(
        "Fill",
        typeof(Brush),
        typeof(EllipseButton),
        new FrameworkPropertyMetadata(new SolidColorBrush(Colors.Gray)));

    public Brush Brush
    {
        get
        {
            return (Brush)GetValue(BrushProperty);
        }
        set
        {
            SetValue(BrushProperty, value);
        }
    }

    public EllipseButton()
    {
        InitializeComponent();
    }
}

Best Answer

Your property is called "Fill" not "Brush":

public static readonly DependencyProperty BrushProperty = DependencyProperty.Register(
        "Fill", //Error is here
        typeof(Brush),
        typeof(EllipseButton),
        new FrameworkPropertyMetadata(new SolidColorBrush(Colors.Gray)));

Change that to:

public static readonly DependencyProperty BrushProperty = DependencyProperty.Register(
        "Brush", 
        typeof(Brush),
        typeof(EllipseButton),
        new FrameworkPropertyMetadata(new SolidColorBrush(Colors.Gray)));
Related Topic