依赖属性,在构造函数中更改通知和设定值
-
26-09-2019 - |
题
我有3个依赖属性A,B,C的类。这些属性的值由构造和特性A,B或C的变化的每一次一项,该方法重新计算()被调用。现在构造的执行期间这些方法被称为3倍,这是因为3个属性A,B,C而变化。 Hoewever这不是必要的,因为该方法重新计算()不能做任何事情没有所有3个属性设置非常有用。那么什么是属性更改通知,但规避在构造该变更通知的最佳方式?我想到了在构造函数中添加属性更改通知,但随后的DPChangeSample类的每个对象将随时添加越来越多的更改通知。感谢您的任何提示!
class DPChangeSample : DependencyObject
{
public static DependencyProperty AProperty = DependencyProperty.Register("A", typeof(int), typeof(DPChangeSample), new PropertyMetadata(propertyChanged));
public static DependencyProperty BProperty = DependencyProperty.Register("B", typeof(int), typeof(DPChangeSample), new PropertyMetadata(propertyChanged));
public static DependencyProperty CProperty = DependencyProperty.Register("C", typeof(int), typeof(DPChangeSample), new PropertyMetadata(propertyChanged));
private static void propertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((DPChangeSample)d).recalculate();
}
private void recalculate()
{
// Using A, B, C do some cpu intensive calculations
}
public DPChangeSample(int a, int b, int c)
{
SetValue(AProperty, a);
SetValue(BProperty, b);
SetValue(CProperty, c);
}
}
解决方案
你可以试试这个?
private bool SupressCalculation = false;
private void recalculate()
{
if(SupressCalculation)
return;
// Using A, B, C do some cpu intensive caluclations
}
public DPChangeSample(int a, int b, int c)
{
SupressCalculation = true;
SetValue(AProperty, a);
SetValue(BProperty, b);
SupressCalculation = false;
SetValue(CProperty, c);
}
其他提示
使用DependencyObject.SetValueBase
。这绕过任何元数据规定,所以你的PropertyChanged不会被调用。请参阅 MSDN
设置A,B和C,当你不想要执行重新计算(),除非所有的三个属性设置,但它会从构造函数叫什么名字?这是正确的?
如果是这样,你能不能只把支票在重新计算接近顶部检查所有三个属性设置,并决定是否要执行或不....
这会工作,因为你提到
作为方法重新计算()不能做 没有任何东西都3真正有用 属性中设定。
不隶属于 StackOverflow