Search code examples
c#windowsxamlwinui-3winui

How do I clear a RatingControl and make it 0 stars in WinUI 3?


My UI:

enter image description here

Here is my XAML:

<StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="4">
    <RatingControl x:Name="mainRating" Margin="5, 10, 10, 0" HorizontalAlignment="Left" VerticalAlignment="Center" VerticalContentAlignment="Center" AutomationProperties.Name="Simple RatingControl" IsClearEnabled="True" IsReadOnly="False" ValueChanged="MainRating_ValueChanged" />
    <Button x:Name="clearRatingButton" Content="Clear Rating" Click="ClearRatingButton_Click" Visibility="Collapsed" />
</StackPanel>

And here is my code for when the "Clear Rating" button is clicked:

private void ClearRatingButton_Click(object sender, RoutedEventArgs e)
{
    mainRating.Value = 0.0;
    clearRatingButton.Visibility = Visibility.Collapsed;
}

private void MainRating_ValueChanged(RatingControl sender, object args)
{
    clearRatingButton.Visibility = Visibility.Visible;
}

But whenever that code is called, the stars on the control in the UI is always set to 1 star, not 0. Why?

enter image description here


Solution

  • All dependency properties have associated metadata with it. The public instance's property get/set methods are merely wrappers over dependency properties GetValue and SetValue methods.

    And you can also reset the value to it's default value using the ClearValue method.

    In the case of RatingControl, that would be a code like this:

    mainRating.ClearValue(RatingControl.ValueProperty);
    

    Note this can be seen as a shortcut to:

    var dp = RatingControl.ValueProperty;
    var def = dp.GetMetadata(typeof(RatingControl)).DefaultValue; // -1d
    mainRating.SetValue(dp, def);