在 Silverlight 中,可以定义 DependencyProperty 的最小/最大值吗?
例如,我有一个依赖属性可以更改 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您要在 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:
除此之外,在 PropertyChangedCallback 内部,典型的模式将在抛出异常之前恢复不正确/超出范围的值。
如果您不执行恢复,实际上仍然会设置超出范围的值,并且您的状态将无效。
您将在某些 Silverlight 工具包中看到这种“穷人的强制手段”的示例。 这是AutoCompleteBox.cs 源。
该模式类似于:
您还可以以类似的方式实现您自己的“只读”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:
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.