خصائص التبعية ، وتغيير الإخطار وإعداد القيم في المُنشئ

StackOverflow https://stackoverflow.com/questions/3028680

سؤال

لدي فصل مع 3 خصائص التبعية A ، B ، ج. يتم تعيين قيم هذه الخصائص بواسطة المنشئ وفي كل مرة تتغير فيها أحد الخصائص A أو B أو C ، تسمى الطريقة إعادة حساب (). الآن أثناء تنفيذ المُنشئ ، تسمى هذه الطريقة 3 مرات ، لأن الخصائص الثلاثة A ، B ، C تم تغييرها. However هذا ليس ضروريًا لأن الطريقة التي تتم إعادة حسابها () لا يمكنها فعل أي شيء مفيد حقًا دون تعيين جميع الخصائص الثلاثة. إذن ما هي أفضل طريقة لإخطار تغيير الممتلكات ولكن التحايل على إشعار التغيير هذا في المنشئ؟ فكرت في إضافة الإخطار الذي تم تغيير خاصية الخاصية في المُنشئ ، ولكن بعد ذلك ، سيضيف كل كائن من فئة 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.

أنت لا تريد تنفيذ RESALCULITY () ما لم يتم تعيين جميع الخصائص الثلاثة ، ولكن في ما يتم استدعاؤه من المُنشئ عند تعيين A و B و C؟ هل هذا صحيح؟

إذا كان الأمر كذلك ، فلا يمكنك فقط وضع شيك في إعادة حساب بالقرب من الأعلى للتحقق من أن جميع الخصائص الثلاثة يتم تعيينها وتحديد ما إذا كنت تريد التنفيذ أم لا ....

سيعمل هذا لأنك تذكر ذلك

نظرًا لأن الطريقة التي يتم إعادة حسابها () لا يمكن أن تفعل أي شيء مفيد حقًا دون تعيين جميع الخصائص الثلاثة.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top