سؤال

ودعونا نقول لدي فئة بسيطة

public class Person
{
  public string Name { get; set; }

  private int _age;
  public int Age
  {
    get { return _age; }
    set
    {
      if(value < 0 || value > 150)
        throw new ValidationException("Person age is incorrect");
      _age = value;
    }
  }
}

وبعد ذلك أريد أن إعداد ملزمة لهذه الفئة:

txtAge.DataBindings.Add("Text", dataSource, "Name");

والآن إذا دخلت قيمة العمر غير صحيحة في مربع النص (ويقول 200) سيتم ابتلع الاستثناء في واضع وأنا لن تكون قادرة على فعل أي شيء على الإطلاق حتى أصحح القيمة في مربع النص. I يعني ان النص لن تكون قادرة على تفقد التركيز. كل شيء صامت - عدم وجود أخطاء - لا يمكنك أن تفعل أي شيء (حتى إغلاق النموذج أو تطبيق كامل) حتى تقوم بتصحيح قيمة

ويبدو وكأنه علة، ولكن السؤال هو: ما هو الحل لهذه

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

المحلول

حسنا، هنا هو الحل:

ونحن بحاجة للتعامل مع الحدث BindingComplete من BinsingSource، CurrencyManager أو فئة BindingBanagerBase. رمز يمكن أن تبدو مثل هذا:

/* Note the 4th parameter, if it is not set, the event will not be fired. 
It seems like an unexpected behavior, as this parameter is called 
formattingEnabled and based on its name it shouldn't affect BindingComplete 
event, but it does. */
txtAge.DataBindings.Add("Text", dataSource, "Name", true)
.BindingManagerBase.BindingComplete += BindingManagerBase_BindingComplete;

...

void BindingManagerBase_BindingComplete(
  object sender, BindingCompleteEventArgs e)
{
  if (e.Exception != null)
  {
    // this will show message to user, so it won't be silent anymore
    MessageBox.Show(e.Exception.Message); 
    // this will return value in the bound control to a previous correct value
    e.Binding.ReadValue();
  }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top