依赖属性依赖于另一个属性
如何注册一个依赖属性,其值是使用另一个依赖属性的值计算的?
由于 .NET 属性包装器在运行时被 WPF 绕过,因此不应在 getter 和 setter 中包含逻辑。解决方案通常是使用PropertyChangedCallback。但这些被声明为静态的。
例如,完成这个人为任务的正确方法是什么:
public bool TestBool
{
get { return (bool)GetValue(TestBoolProperty); }
set
{
SetValue(TestBoolProperty, value);
TestDouble = ((value)?(100.0):(200.0)); // HERE IS THE DEPENDENCY
}
}
public static readonly DependencyProperty TestBoolProperty =
DependencyProperty.Register("TestBool", typeof(bool), typeof(ViewModel));
public double TestDouble
{
get { return ((double)GetValue(TestDoubleProperty)); }
set { SetValue(TestDoubleProperty, value); }
}
public static readonly DependencyProperty TestDoubleProperty =
DependencyProperty.Register("TestDouble", typeof(double), typeof(ViewModel));
只要依赖不是循环的,是否有正确的方法来完成这个任务?
How can one register a dependency property whose value is calculated using the value of another dependency property?
Because the .NET property wrappers are bypassed by WPF at run-time, one should not include logic in the getters and setters. The solution to that is typically to use PropertyChangedCallback
s. But those are declared static.
For example, what is the proper way to accomplish this contrived task:
public bool TestBool
{
get { return (bool)GetValue(TestBoolProperty); }
set
{
SetValue(TestBoolProperty, value);
TestDouble = ((value)?(100.0):(200.0)); // HERE IS THE DEPENDENCY
}
}
public static readonly DependencyProperty TestBoolProperty =
DependencyProperty.Register("TestBool", typeof(bool), typeof(ViewModel));
public double TestDouble
{
get { return ((double)GetValue(TestDoubleProperty)); }
set { SetValue(TestDoubleProperty, value); }
}
public static readonly DependencyProperty TestDoubleProperty =
DependencyProperty.Register("TestDouble", typeof(double), typeof(ViewModel));
As long as the dependency is not circular, is there a proper means to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯...我认为你最好看看依赖属性
Hmmm... I think you'd better look at dependency properties value coercion. Here is an example with coercion:
你实际上是对的,你应该使用PropertyChangedCallback。方法如下:
You're actually correct, you should use PropertyChangedCallback. Here's how: