gpt4 book ai didi

c# - 如何正确绑定(bind)和更新 Xamarin.Forms ListView?

转载 作者:太空狗 更新时间:2023-10-29 21:08:42 26 4
gpt4 key购买 nike

使用 MVVM 模式,我有一个模型、 View 模型和 View ,其中包含一个 ListView。 ListView 绑定(bind)到 ViewModel 的成员,该成员是 Model 类的 ObservableCollection。我可以获得初始显示的绑定(bind),并且可以在对 View 进行操作时更新模型类上相应行的属性,但是我无法刷新 View ,从 ObservableCollection 中的模型类中提取数据。 ListView 类不包含无效或强制刷新的方法,这将解决我的问题。如何在更新模型上的数据后让 ListView 刷新?

这是我正在尝试做的一个简单示例:每一行都包含一个按钮和一个标签。单击按钮后,我可以更新标签,这将反射(reflect)在屏幕上。我需要做的是更新模型,这反过来又会强制更新 View 。但是,我无法让它工作。在实际应用中,Model 的更新将在业务逻辑层,而不是在 View 中,之后我需要强制刷新 ListView。

示例代码:

using System;
using System.Collections.ObjectModel;
using Xamarin.Forms;

namespace ListViewTest
{
public class Model
{
public static int ids = 0;
public Model(string count)
{
Id = +1;
Count = count;
}
public int Id { get; set; }
public string Count { get; set; }
}

public class ModelList : ObservableCollection<Model>
{
}

public class ViewModel
{
ModelList list = new ModelList();
public ModelList ViewModelList
{
get { return list; }
set
{
list = value;
}
}
}

public partial class MainPage : ContentPage
{
public ViewModel viewModel;

public class DataCell : ViewCell
{
public DataCell()
{
var Btn = new Button();
Btn.Text = "Click";
var Data = new Label();
Data.SetBinding(Label.TextProperty,"Count");
Btn.Clicked += (object sender, EventArgs e) =>
{
Model model = (Model)(((Button)sender).Parent.BindingContext);
int count = Convert.ToInt32(model.Count);
count++;
model.Count = count.ToString();

// Need to refresh ListView from data source here... How???
};

StackLayout s = new StackLayout();
s.Orientation = StackOrientation.Horizontal;
s.Children.Add(Btn);
s.Children.Add(Data);
this.View = s;
}
}

public MainPage ()
{
viewModel = new ViewModel();
viewModel.ViewModelList.Add(new Model("0"));
viewModel.ViewModelList.Add(new Model("0"));
InitializeComponent();
}

public void InitializeComponent()
{
ListView listView = new ListView
{
ItemsSource = viewModel.ViewModelList,
ItemTemplate = new DataTemplate(() =>
{
return new DataCell();
})
};
Content = listView;
}
}
}

最佳答案

我认为您的模型需要实现 INotifyPropertyChanged。因此 UI 知道模型中的值已更改

像这样:

public class Model : INotifyPropertyChanged
{
// boiler-plate
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, string propertyName)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}

// props
private string _count;
public string Count
{
get { return _count; }
set { SetField(ref _count, value, "Count"); }
}
}

关于c# - 如何正确绑定(bind)和更新 Xamarin.Forms ListView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25004275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com