Skip to content

Show how to coerce a value for a custom dependency property #3271

@michael-hawker

Description

@michael-hawker
Contributor

UWP doesn't support the coercion method that WPF did, but there is a pattern the WinUI team uses:

https://github.com/microsoft/microsoft-ui-xaml/blob/3d2d5a82eea26475c154e1fdf7c589e97365eeef/dev/ProgressRing/ProgressRing.cpp#L147-L164

It'd be great to have a concrete C++ and C# example to show how to do this common pattern within the docs, as it's important to do in the property change callback and not the property setter (as per the docs calling out that SetValue/property setter is short-cuted by the XAML parser).


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Activity

added
doc-enhancementfeedback is about suggested additions/improvements to the article, but customer is not blocked
on Aug 3, 2021
michael-hawker

michael-hawker commented on Aug 9, 2021

@michael-hawker
ContributorAuthor

This is a link for more about the finally construct used in the C++ code-base of WinUI: https://docs.microsoft.com/cpp/code-quality/c26448

Not sure if there's a better way than just setting flag back in C# land... e.g.

private bool _isUpdating;

private static void PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if (d is MyClass thing && !thing._isUpdating)
    {
        thing._isUpdating = true;

        thing.CoerceValues();
        
        thing._isUpdating = false;
    }
}

private void CoerceValues()
{
    if (Value < Minimum)
    {
        Value = Minimum;
    }
    else if (Value > Maximum)
    {
        Value = Maximum;
    }
}

@codendone any suggestions for this pattern?

codendone

codendone commented on Aug 12, 2021

@codendone
Contributor

I think that is the best pattern I've seen. @MikeHillberg, are you aware of any better patterns?

added a commit that references this issue on Feb 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Pri2doc-enhancementfeedback is about suggested additions/improvements to the article, but customer is not blockedplatform/techuwp/prod

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

    Development

    No branches or pull requests

      Participants

      @jwmsft@michael-hawker@PRMerger7@PRMerger20@codendone

      Issue actions

        Show how to coerce a value for a custom dependency property · Issue #3271 · MicrosoftDocs/windows-dev-docs