从后面的代码更新列表视图

时间:2012-03-11 19:31:48

标签: c# wpf binding

我在xaml中有以下代码:

    <ListView Name="listView1" IsSynchronizedWithCurrentItem="True" >
        <ListView.View>
            <GridView>
                <GridViewColumn Header="MyList">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Cost, Mode=TwoWay}"></TextBlock>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

我的代码背后有:

public partial class LogIn : UserControl,  INotifyCollectionChanged
{
    class Product
    {
        public string Name { get; set; }
        public int Cost { get; set; }
    }

    ObservableCollection<Product> MyList = new ObservableCollection<Product>()
    {
        new Product(){ Cost=14},
        new Product(){ Cost=15},
        new Product(){ Cost=5},
        new Product(){ Cost=20}
    };

    event NotifyCollectionChangedEventHandler INotifyCollectionChanged.CollectionChanged
    {
        add { throw new NotImplementedException(); }
        remove { throw new NotImplementedException(); }
    }

    // constructor
    public LogIn()
    {
        InitializeComponent();

        listView1.DataContext = MyList;
    }

    private void button5_Click(object sender, RoutedEventArgs e)
    {
        this.MyList[0].Cost = 123456789;
        // !!!!!!!!!!!!!!! I want the listview to update when I press this button
    }

当我更新最后一个方法时,listview不会改变。我该怎么办才能用代码隐藏更新listview成本值?


修改

感谢SLaks,我对我的Product类进行了以下更改,并且它有效。

    public class Product : INotifyPropertyChanged
    {
        private int _cost;
        public string Name { get; set; }
        public int Cost
        {
            get
            {
                return _cost;
            }
            set
            {
                _cost = value; 
                OnPropertyChanged("Cost");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

我还在usercontroll的构造函数中添加了以下行:

   listView1.ItemsSource = MyList;

1 个答案:

答案 0 :(得分:2)

您需要在INotifyPropertyChanged类中实现Product,以便WPF知道您的属性何时更改。