在 Silverlight 中,可以定义 DependencyProperty 的最小/最大值吗?

发布于 2024-07-30 02:00:47 字数 201 浏览 2 评论 0原文

例如,我有一个依赖属性可以更改 Canvas 的 ScaleTransform,但如果它低于零,则会引发错误。 当然,如果发生这种情况,我可以在代码中将其强制为零,但我宁愿使用更好的方法,例如使用 udouble (无符号双精度),这在 Silverlight 中不存在,甚至设置最小/最大值DependencyProperty 中的某处。

这里最好的方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

波浪屿的海角声 2024-08-06 02:00:48

如果您要在 DependencyProperty 中处理此问题,我建议您在 PropertyChangedCallback,它验证该值是否在正确的范围内,如果不正确则覆盖它。

您还可以在依赖属性之外处理此问题。 例如:

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:

吐个泡泡 2024-08-06 02:00:48

除此之外,在 PropertyChangedCallback 内部,典型的模式将在抛出异常之前恢复不正确/超出范围的值。

如果您不执行恢复,实际上仍然会设置超出范围的值,并且您的状态将无效。

您将在某些 Silverlight 工具包中看到这种“穷人的强制手段”的示例。 这是AutoCompleteBox.cs 源

该模式类似于:

   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");
        }

您还可以以类似的方式实现您自己的“只读”Silverlight 依赖属性,尽管它需要一个私有字段来指示您是在设置还是恢复该值。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文