user3154369
user3154369

Reputation: 159

ListView - Binding listviewitem data to an object

Let's assume I have the following ListView:

<ListView Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="IsTrue" DisplayMemberBinding="{Binding Path=IsTrue}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=name}" />
        </GridView>
    </ListView.View>
</ListView>

And the following Test class I want to bind:

public class Test
{
    public Test(Boolean IsTrue, string name)
    {
        this.IsTrue = IsTrue;
        this.name = name;
    }

    public Boolean IsTrue { get; set; }
    public string name { get; private set; }
}

Here's the command I use to add ListViewItem:

Test a = new Test(false, "a");
listView.Items.Add(a);

Now when I try to change the a object IsTrue value the value IsTrue on ListView won't update. Why is so?

Upvotes: 1

Views: 532

Answers (2)

Zer0
Zer0

Reputation: 7364

public class Test : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
    {
        var e = PropertyChanged;
        if (e != null)
            e(this, args);
    }

    private bool isTrue;
    public Boolean IsTrue
    {
        get { return isTrue; }
        set
        {
            if (isTrue == value)
                return;
            isTrue = value;
            OnPropertyChanged(new PropertyChangedEventArgs("IsTrue"));
        }
    }

    public string Name { get; private set; }

    public Test(Boolean isTrue, string name)
    {
        this.isTrue = isTrue;
        Name = name;
    }
}

Upvotes: 2

Haojie
Haojie

Reputation: 5713

You have to implement INotifyPropertyChanged interface for class Test, so when you change the Property, the UI will get notified.

Upvotes: 2

Related Questions