Erez
Erez

Reputation: 6446

Wpf - problem with binding to a collection item

this is my simple xaml that shows in a textbox the age of the first person in a collection of persons. I don't understand I after click the age isn't changing.

 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="132*" />
        <RowDefinition Height="179*" />
    </Grid.RowDefinitions>
    <TextBlock Text="{Binding Persons[0].Age}" />
    <Button Grid.Row="1" Click="Button_Click">Change Age</Button>
</Grid>

this is the code behind of the xaml:

 public partial class MainWindow : Window
{
    public ObservableCollection<Person> Persons { get; set; }

    public MainWindow() {
        Persons = new ObservableCollection<Person>();
        Persons.Add(new Person{Age = -1});

        DataContext = this;
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e) {
        (Persons[0] as Person).Age = 5;
    }
}

this is class person:

 public class Person : INotifyPropertyChanged
{
    private int _age;

    public int Age
    {
        get { return _age; }
        set
        {
            _age = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("Age"));
            }
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

Upvotes: 0

Views: 616

Answers (3)

Jason
Jason

Reputation: 1969

I tried your code and it worked perfectly for me. I even changed the button click handler so I could keep clicking and see the TextBlock update.

private void Button_Click(object sender, RoutedEventArgs e)
{
    (Persons[0] as Person).Age = (Persons[0] as Person).Age + 1;
}

Upvotes: 0

Dean Chalk
Dean Chalk

Reputation: 20451

Your code is correct, you have implemented INotifyPropertyChanged on your class so all should be good.

Are you sure its not changing ?

Upvotes: 0

dcarneiro
dcarneiro

Reputation: 7150

that's probably because the view don't catch that one property of one element of the list changed. It only catches that the list changed (add or remove elements)

private void Button_Click(object sender, RoutedEventArgs e) {

    (Persons[0] as Person).Age = 5;
    Person p = Persons.First();
    Persons.Remove(0);
    Persons.Add(p);
}

Upvotes: 1

Related Questions