What's wrong with my data binding?

I copied the code from the empty panorama project and made some adjustments, but something is wrong somewhere.

I have my textbox set:

<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 in MainViewModel()

:

public CurrentPlaceNowModel CurrentPlaceNow = new CurrentPlaceNowModel();

      

Finally, I added the buttoncick button modifier:

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

      

Now why is nothing showing in the textbox?

+3


source to share


2 answers


Your anchor should be navigating the ViewModel. ElementName binding 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}" />

      



Make sure the ViewModel property is formatted correctly:

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

      

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

+4


source


You are using ElementName incorrectly. ElementName is when you want to bind to another XAML control instead of the (view) model.



To bind to a model, set an instance of that model to the DataContext property and bind only the Path.

0


source







All Articles