tags:

views:

229

answers:

3

Hi all,

I have 2 controls that both bind to the same dependency property "Weather". In the first control you put the current weather, the other one displays a forecast.

In my XAML of the first control I bind a TextBox that contains the "Humidity" as follows.

<TextBox Text="{Binding Weather.Humidity}" />

Whenever the Humidity changes, I want the other control to do something, however changing only Humidity does not change the Weather - so the other control it not notified. Changing the Humidity should change the entire forecast.

(I'm not actually writing a weather app., but just using the above as an example)

My question: what is the proper way to do this? The only way I can think of is setting a SourceUpdated event handler on the TextBox that touches the Weather property. Is there a more elegant way to do this?

Thanks

+1  A: 

The default value for the UpdateSourceTrigger property on a TextBox binding is 'LostFocus' one thing you should do is change this to PropertyChanged, then the Humidity property will reflect any changes as you enter them in the TextBox.

Next, you want to make sure that your Weather Class implements INotifyPropertyChanged, like so:

    public class Weather : INotifyPropertyChanged
 {
  private int myHumidity;
  public int Humidity
  {
   get
   {
    return this.myHumidity;
   }
   set
   {
    this.myHumidity = value;
    NotifyPropertyChanged("Humidity");
   }
  }

  private void NotifyPropertyChanged(String info)
  {
   if (PropertyChanged != null)
   {
    PropertyChanged(this, new PropertyChangedEventArgs(info));
   }
  }

  #region INotifyPropertyChanged Members

  public event PropertyChangedEventHandler PropertyChanged;

  #endregion
 }

This will ensure that the UI is notified of any changes to the Humidity property.

rmoore
A: 

I assume that the reason why you want the other control to do something is because humidity affects some other property of the weather/forecast. In this case, you implement INotifyPropertyChanged, as in rmoore's answer, and you make sure that when humidity is modified, it either explicitly changes the other property, triggering its notification update, or it sends a notification for its update, like this:

private int myHumidity;
            public int Humidity
            {
                    get
                    {
                            return this.myHumidity;
                    }
                    set
                    {
                            this.myHumidity = value;
                            NotifyPropertyChanged("Humidity");
                            NotifyPropertyChanged("MyOtherProperty");
                    }
            }
Yes, this best matches my scenario - thanks I will implement it like this
Robbert Dam
A: 
Tawani