سؤال

وعندما ربط هذا الكائن

public class MyObject
{ 
  public AgeWrapper Age
{
get;
set;
}
}

public class AgeWrapper
{
public int Age
{
get;
set;
}
}

وعلى شبكة الملكية، ما هو مبين في القسم قيمة الشبكة الملكية هو اسم فئة من AgeWrapper، ولكن قيمة AgeWrapper.Age.

وهناك على أية حال لتجعل من ذلك أن في الشبكة الملكية يمكنني أن تظهر قيمة الكائن المركب (في هذه الحالة، انها AgeWrapper.Age)، بدلا من اسم فئة من هذا الكائن المركب؟

هل كانت مفيدة؟

المحلول

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

public class AgeWrapperConverter : ExpandableObjectConverter
{
  public override bool CanConvertTo(ITypeDescriptorContext context, 
                                    Type destinationType)
  {
    // Can always convert to a string representation
    if (destinationType == typeof(string))
      return true;

    // Let base class do standard processing
    return base.CanConvertTo(context, destinationType);
  }

  public override object ConvertTo(ITypeDescriptorContext context, 
                                   System.Globalization.CultureInfo culture, 
                                   object value, 
                                   Type destinationType)
  {
    // Can always convert to a string representation
    if (destinationType == typeof(string))
    {
      AgeWrapper wrapper = (AgeWrapper)value;
      return "Age is " + wrapper.Age.ToString();
    }

    // Let base class attempt other conversions
    return base.ConvertTo(context, culture, value, destinationType);
  }  
}

لاحظ أن فإنه يرث من ExpandableObjectConverter. وذلك لأن الطبقة AgeWrapper له خاصية طفل يدعى AgeWrapper.Age التي تحتاج إلى أن يتعرض لها من خلال وجود زر + بجانب إدخال AgeWrapper في الشبكة. إذا صفك لم يكن لديها أي خصائص الطفل الذي أردت فضح ثم بدلا من وراثة TypeConverter. الآن تطبيق هذا المحول لصفك ...

[TypeConverter(typeof(AgeWrapperConverter))]
public class AgeWrapper
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top