Data Binding and throwing exception in setter

后端 未结 1 495
慢半拍i
慢半拍i 2020-12-11 05:35

Let\'s say I have a simple class

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

  private int _age;
  public int Age
  {
    get { return _age; }
         


        
相关标签:
1条回答
  • 2020-12-11 05:45

    Ok, here is the solution:

    We need to handle BindingComplete event of BinsingSource, CurrencyManager or BindingBanagerBase class. The code can look like this:

    /* 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 讨论(0)
提交回复
热议问题