Xamarin.Forms更新ListView中的一个元素

时间:2017-06-24 12:14:39

标签: listview mvvm xamarin.forms

我想在Xamarin.Forms中使用mvvm更新listview元素。我在网上关注了一些教程,现在我可以添加新项目并删除任何项目到我的列表视图。 但是我无法更新任何特定项目

这是我的ViewModel类:

public class CarsViewModels : INotifyPropertyChanged
{
    private ObservableCollection<Car> items;

    public ObservableCollection<Car> Items
    {
        get { return items; }

        set
        {
            items = value;
            OnPropertyChanged("Items");
        }
    }

    public CarsViewModels()
    {
        Items = new ObservableCollection<Car>() 
        {
            new Car()
            {
                CarID = 1,
                Make = "Tesla Model S"
            },
              new Car()
            {
                CarID = 2,
                Make = "Audi R8"
            },
        };
    }

    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged([CallerMemberName]string propertyName = "") =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

这是添加,删除和更改我的xaml.cs文件中的方法

private void AddNewItemClicked(object sender, EventArgs e)
    {
        items.Add(new Car{CarID = 3, Make = "new car"});
    }

    private void RemoveItemClicked(object sender, EventArgs e)
    {
        Button clickedITem = (Button)sender;
        var clickedCar = (Car) clickedITem.BindingContext;

        items.Remove(clickedCar);
    }

    private void ChangeThisItemClicked(object sender, EventArgs e)
    {
        Button button = (Button)sender;
        var clickedCar = (Car)clickedITem.BindingContext;

        var changedItem = items.FirstOrDefault(x => x.CarID == clickedCar.CarID);

        if (changedItem != null)
        {
            changedItem.Make = "text has changed";
        }
    }

添加和删除方法有效,但我无法更新汽车模型的make属性。有什么帮助吗?

0 个答案:

没有答案