Mech0z Mech0z - 1 year ago 50
C# Question

wpf databinding not updating from a property

I want movieinformation updated in a some textboxes depending on the selected movie

I have

public Movie SelectedMovie { get; set; }


in my viewmodel which is what my datacontext is set at

And whenever a movie is selected in my list it updates "SelectedMovie"

But only the first movie updates the textblock

<TextBlock Grid.ColumnSpan="2" Text="{Binding Path=SelectedMovie.Name}" FontSize="17" />


(The one selected when the application loads)

So not really sure why its not changing the text when I select a new movie in the list?

Movie class:

using System;
using System.ComponentModel;

namespace MovieDB3.Models
{
class Movie : INotifyPropertyChanged
{
public Movie(string name)
{
this.name = name;
}

private string name;
public string Name
{
get { return name; }
set
{
name = value;
InvokePropertyChanged("Name");
}
}
public int Id { get; set; }
private double rating;
public double Rating
{
get { return rating; }
set
{
rating = value;
InvokePropertyChanged("Rating");
}
}

public DateTime Release { get; set; }
public TimeSpan Runtime { get; set; }
public String Trailer { get; set; }

public event PropertyChangedEventHandler PropertyChanged;

private void InvokePropertyChanged(String propertyName)
{
PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
PropertyChangedEventHandler changed = PropertyChanged;

if (changed != null) changed(this, e);
}
}
}

Answer Source

You have to fire PropertyChanged event in the setter of the SelectedMovie property in order to notify the binding that something has changed:

private Movie selectedMovie;

public Movie SelectedMovie
{
    get
    {
        return selectedMovie;
    }
    set
    {
        selectedMovie = value;
        InvokePropertyChanged("SelectedMovie");
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download