Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's wrong with my databinding?

I've copied code from the blank panorama project and made some adjustments, but somewhere something ain't right.

I've got my textblock set up:

<TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding ElementName=CurrentPlaceNow, Path=Temperature}" />

My model looks like this:

public class CurrentPlaceNowModel : INotifyPropertyChanged
{
    #region PropertyChanged()
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion

    private string _temperature;
    public string Temperature
    {
        get
        {
            return _temperature;
        }
        set
        {
            if (value != _temperature)
            {
                _temperature = value;
                NotifyPropertyChanged("Temperature");
            }
        }
    }
}

And defined defined in the MainViewModel():

public CurrentPlaceNowModel CurrentPlaceNow = new CurrentPlaceNowModel();

Finally I've added a modifier to a buttonclick:

App.ViewModel.CurrentPlaceNow.Temperature = "foo";

Now, why isn't anything showing up in the textbox?

like image 447
Jason94 Avatar asked Apr 02 '26 11:04

Jason94


1 Answers

Your Binding should navigate through the ViewModel. Binding to an ElementName tries to look at another object in the Visual Tree.

Change your Binding to this:

<TextBlock 
    Grid.Column="0" 
    Grid.Row="0" 
    Text="{Binding CurrentPlaceNow.Temperature}" />

Verify your ViewModel's property is formatted properly:

private CurrentPlaceNowModel _CurrentPlaceNow = new CurrentPlaceNowModel();
public CurrentPlaceNowModel CurrentPlaceNow
{
   get { return _CurrentPlaceNow; }
   set
   {
       _CurrentPlaceNow = value;
       NotifyPropertyChanged("CurrentPlaceNow");
   }
}

As long as your View's DataContext is your MainViewModel, you are good to go.

like image 167
Jeremiah Avatar answered Apr 08 '26 13:04

Jeremiah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!