Domanda

Diciamo che ho una classe semplice

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;
    }
  }
}

Poi voglio installare un binding per questa classe:

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

Ora, se entro in valore di età non corretta nella casella di testo (ad esempio 200) l'eccezione nel setter sarà inghiottito e non sarò in grado di fare nulla fino a quando correggo il valore nella casella di testo. Voglio dire la casella di testo non sarà in grado di perdere fuoco. E 'tutto in silenzio - nessun errore -. Non si può fare nulla (anche chiudere il modulo o l'intera applicazione) fino a correggere il valore

Sembra un bug, ma la domanda è: che cosa è una soluzione per questo

È stato utile?

Soluzione

Ok, ecco la soluzione:

Abbiamo bisogno di gestire l'evento BindingComplete di BinsingSource, CurrencyManager o di classe BindingBanagerBase. Il codice può essere simile a questo:

/* 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();
  }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top