James B
James B

Reputation: 9595

Style DataTrigger not updating Custom Control Dependency Property

I've defined a custom control that allows me to draw a series of arcs that result in a segmented circle. In this control I've defined a dependency property that allows me to set the number of segments to draw, i.e.,

public int SegmentCount
{
  get => (int) GetValue( SegmentCountProperty );
  set => SetValue( SegmentCountProperty, value );
}

public static readonly DependencyProperty SegmentCountProperty =
            DependencyProperty.Register( nameof(SegmentCount), typeof( int ), typeof( MyCustomControl ), new PropertyMetadata( 1 ) );

I want to set this property in xaml according to a data trigger defined in a style as follows

<Style x:Key="MyCustomControlStyle" TargetType="local:MyCustomControl">
    <Setter Property="SegmentCount" Value="0"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsActive}" Value="True">
            <Setter Property="SegmentCount" Value="4"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding IsActive}" Value="False">
            <Setter Property="SegmentCount" Value="0"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

However, the "False" DataTrigger that attempts to set the SegmentCount property back to 0 doesn't appear to update the view. If I set the Stroke property as well (which i don't want to do) like this

<Style x:Key="MyCustomControlStyle" TargetType="local:MyCustomControl">
    <Setter Property="SegmentCount" Value="0"/>
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsActive}" Value="True">
            <Setter Property="SegmentCount" Value="4"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding IsActive}" Value="False">
            <Setter Property="SegmentCount" Value="0"/>
            <Setter Property="Stroke" Value="Green"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

It seems to kick things along and I get the expected view, albeit with the wrong colour now. Is there a reason why my Dependency property is not updating the view in this scenario? Do I have to tell the framework it has changed similar to a RaiseNotifyProperty changed event?

Upvotes: 0

Views: 540

Answers (1)

Clemens
Clemens

Reputation: 128062

There is no PropertyChangedCallback registered for the SegmentCount property.

It probably just does not trigger rendering. Try to set Framework​Property​Metadata​Options.AffectsRender:

public static readonly DependencyProperty SegmentCountProperty =
    DependencyProperty.Register(
        nameof(SegmentCount), typeof(int), typeof(MyCustomControl),
        new FrameworkPropertyMetadata(
            1, FrameworkPropertyMetadataOptions.AffectsRender));

Upvotes: 2

Related Questions