views:

115

answers:

2

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?

+3  A: 

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:

Jon Galloway
That's what I ended up doing – changing it in the PropertyChangedCallback, but I was looking for an alternative. Thanks for the extra links here.
sfjedi
Would you post an example of how you can safely/cleanly override the value that was just changed? If you change it, it would fire the whole OnChanged event/callback a second time.
Stephen Price
A: 

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.

Jeff Wilcox