gpt4 book ai didi

c# - 如何使用 ReactiveList 以便在添加新项目时更新 UI

转载 作者:行者123 更新时间:2023-11-30 20:45:54 27 4
gpt4 key购买 nike

我正在创建一个带有列表的 Xamarin.Forms 应用程序。 itemSource 是一个 react 列表。但是,向列表中添加新项目不会更新 UI。这样做的正确方法是什么?

列表定义

_listView = new ListView();
var cell = new DataTemplate(typeof(TextCell));
cell.SetBinding(TextCell.TextProperty, "name");
cell.SetBinding(TextCell.DetailProperty, "location");
_listView.ItemTemplate = cell;

绑定(bind)

this.OneWayBind(ViewModel, x => x.monkeys, x => x._listView.ItemsSource);
this.OneWayBind(ViewModel, x => x.save, x => x._button.Command); //save adds new items

查看模型

public class MyPageModel : ReactiveObject
{
public MyPageModel()
{
var canSave = this.WhenAny(x => x.username, x => !String.IsNullOrWhiteSpace(x.Value) && x.Value.Length>5);
save = ReactiveCommand.CreateAsyncTask(canSave, async _ =>
{
var monkey = new Monkey { name = username, location = "@ " + DateTime.Now.Ticks.ToString("X"), details = "More here" };
monkeys.Add(monkey);
username = "";
});
monkeys = new ReactiveList<Monkey>{
new Monkey { name="Baboon", location="Africa & Asia", details = "Baboons are Africian and Arabian Old World..." }
};
_monkeys.ChangeTrackingEnabled = true;
}
private string _username = "";
public string username
{
get { return _username; }
set { this.RaiseAndSetIfChanged(ref _username, value); }
}
private double _value = 0;
public double value
{
get { return _value; }
set { this.RaiseAndSetIfChanged(ref _value, value); }
}
public ReactiveCommand<Unit> save { get; set; }
public ReactiveList<Monkey> _monkeys;
public ReactiveList<Monkey> monkeys
{
get { return _monkeys; }
set { this.RaiseAndSetIfChanged(ref _monkeys, value); }
}
}
public class Monkey
{
public string name { get; set; }
public string location { get; set; }
public string details { get; set; }
}

尝试将 ReactiveList 属性作为普通自动属性以及上面代码中我使用 RaiseAndSetIfChanged 方法的属性。

最佳答案

您的问题是您正在非 UI 线程上更改 monkeys。在其他框架中,这会抛出异常,但在 AppKit/UIKit 中,这只会做奇怪的事情(通常什么都不做)。

    save = ReactiveCommand.Create(canSave);
save.Subscribe(_ =>
{
// Do the part that modifies UI elements (or things bound to them)
// in the RxCmd's Subscribe. This is guaranteed to run on the UI thread
var monkey = new Monkey { name = username, location = "@ " + DateTime.Now.Ticks.ToString("X"), details = "More here" };
monkeys.Add(monkey);
username = "";
});

关于c# - 如何使用 ReactiveList 以便在添加新项目时更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27595482/

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