2009-05-18 16 views
5

powiedzmy mam prostą klasęWiązanie danych i rzuca wyjątek w seter

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

Potem chcesz skonfigurować wiążący dla tej klasy:

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

Teraz jeśli wejdę niepoprawną wartość wiekowej w w polu tekstowym (powiedzmy 200) wyjątek w ustawiaczu zostanie połknięty i nie będę w stanie nic zrobić, dopóki nie poprawię wartości w polu tekstowym. Mam na myśli, że pole tekstowe nie będzie mogło stracić ostrości. Wszystko jest ciche - bez błędów - po prostu nie możesz nic zrobić (nawet zamknąć formularz lub całą aplikację), dopóki nie poprawisz wartości.

Wygląda na błąd, ale pytanie brzmi: co to jest obejście tego problemu?

+1

Czy istnieje powód, dla którego rzucasz wyjątek, a nie wdrażasz IDataErrorInfo? Myślę, że to drugie jest bardziej idiomatyczne podejście w WinForms (i nadal działa ładnie w WPF też). –

Odpowiedz

3

Ok, oto rozwiązanie:

Musimy poradzić BindingComplete wydarzenie BinsingSource, CurrencyManager lub klasy BindingBanagerBase. Kod może wyglądać tak:

/* 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(); 
    } 
} 
+0

huuh ... pomyśl o implementacji IDataErrorInfo –

Powiązane problemy