简体   繁体   中英

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?

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.

You are using ElementName wrong. ElementName is when you want to bind to another XAML control, not to (view)model.

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

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