简体   繁体   中英

Update Textbox control bound to a property

I need to update a TextBox that's bound to a property. In the way I've implemented it it's working fine. Here's the code

private double foo;

public double Foo
{
  get { return foo; }
  set
  {
    foo = value;
    RaisePropertyChanged(() => Foo);
  }
}

But now I need to update the value of this property from another property and the TextBox bound to Foo is not updated. Here's the code

private string foo1

public string Foo1
{
  get { return foo1; }
  set
  {
    foo1 = value;
    foo = 4; // Updating the Foo property indirectly
    RaisePropertyChanged(() => Foo);
    RaisePropertyChanged(() => Foo1);
  }
}

I'm obligated to update the value of the property Foo in that way because Foo and another property are updated each other so I can't update the properties directly because I fall in an infinity recursion.

The question is How I can update the TextBox that is bound to the Foo property when I change the value of the attribute foo ?

I would say you should update the public member Foo in your Foo1 setter. That will cause the RaisePropertyChanged event to fire for Foo .

private string foo1

public string Foo1
{
  get { return foo1; }
  set
  {
    foo1 = value;
    Foo = 4;
    RaisePropertyChanged(() => Foo1);
  }
}

You could call RaisePropertyChanged(() => Foo); whenever you update your private field foo , but unless there is a good reason not to use the property Foo , I would always use it over foo . The intention of set is to have that code run whenever the value of the property changes. In my opinion, setting the private field bypasses the code in set which violates this intention.

EDIT

On another note, if you only want to call RaisePropertyChanged and change the value of Foo when Foo1 changes (not necessarily each time the setter is called), just add a check to see if the value has changed. This will take care of your recursion problem.

set
{
    if(foo1 != value)
    {
       foo1 = value;
       Foo = 4;
       RaisePropertyChanged(() => Foo1);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM