Question

For example, I have a dependency property that changes the ScaleTransform of a Canvas, but if it ever goes below zero it throws an error. Sure, I could just force it to zero in the code if that ever happens, but I'd rather use a better method like using a udouble (unsigned double), which doesn't exist in Silverlight or even setting the min/max values somewhere in the DependencyProperty.

What's the best approach here?

Was it helpful?

Solution

If you're going to handle this in your DependencyProperty, I'd recommend handling it in a PropertyChangedCallback, which validates that the value is in the correct range and overrides it if not.

You could also handle this outside of the dependency property. For instance:

OTHER TIPS

Just to add to that, inside your PropertyChangedCallback, a typical pattern is going to be revert on incorrect/out-of-range values, before throwing an exception.

If you don't do the revert, the out-of-range value will actually still be set, and your state will be invalid.

You'll see examples of this "poor man's coercian" in some of the Silverlight Toolkit. Here's the AutoCompleteBox.cs source.

The pattern is something like:

   int newValue = (int)e.NewValue;
        if (newValue < 0)
        {
            source._ignorePropertyChange = true;
            d.SetValue(e.Property, e.OldValue);

            throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.AutoComplete_OnMinimumPopulateDelayPropertyChanged_InvalidValue, newValue), "value");
        }

You can also implement your own "read-only" Silverlight dependency properties in a similar manner, though it'll require a private field to indicate whether you're setting or reverting the value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top