【问题标题】:How to use ReactiveList so UI is updated when items are added/removed/modified如何使用 ReactiveList 以便在添加/删除/修改项目时更新 UI
【发布时间】:2017-10-03 21:59:48
【问题描述】:

我正在使用 DataGridView 创建一个 WinForms 应用程序。 DataSource 是一个 ReactiveList。但是,向列表中添加新项目不会更新 UI。

视图模型

public class HomeViewModel: ReactiveObject
{
    public ReactiveCommand<object> AddCmd { get; private set; }

    ReactiveList<Model> _models;
    public ReactiveList<Model> Models
    {
        get { return _models; }
        set { this.RaiseAndSetIfChanged(ref _models, value); }
    }

    public HomeViewModel()
    {
        Models = new ReactiveList<Model>() { new Model { Name = "John" } };

        AddCmd = ReactiveCommand.Create();
        AddCmd.ObserveOn(RxApp.MainThreadScheduler);
        AddCmd.Subscribe( _ =>
        {
            Models.Add(new Model { Name = "Martha" });
        });
    }
}

public class Model
{
    public string Name { get; set; }
}

查看

public partial class HomeView : Form, IViewFor<HomeViewModel>
{
    public HomeView()
    {
        InitializeComponent();
        VM = new HomeViewModel();

        this.OneWayBind(VM, x => x.Models, x => x.gvData.DataSource);
        this.BindCommand(VM, x => x.AddCmd, x => x.cmdAdd);
    }

    public HomeViewModel VM { get; set; }

    object IViewFor.ViewModel
    {
        get { return VM; }
        set { VM = (HomeViewModel)value; }
    }

    HomeViewModel IViewFor<HomeViewModel>.ViewModel
    {
        get { return VM; }
        set { VM = value; }
    }
}
  1. 视图始终显示“John”。
  2. 调试订阅显示添加的项目。
  3. 用 ObservableCollection 尝试了相同的结果。How to use ReactiveList so UI is updated when new items are added
  4. 用 IReactiveDerivedList 尝试了相同的结果。 Does ReactiveUI RaiseAndSetIfChanged fire for List<T> Add, Delete, Modify?

【问题讨论】:

  • 你的命令可以简化 btw.. 喜欢 AddCmd = ReactiveCommand.Create(() => Models.Add(.....));

标签: winforms reactiveui


【解决方案1】:

我认为你想要的是 ReactiveBindingList 而不是 ReactiveList。这是用于绑定目的的 ReactiveList 的 WinForms 特定版本。

【讨论】:

  • 谢谢,但是。如果我使用 ReactiveBindingList 我不能共享我的 ViewModel 和 ReactiveBindingList 不能像 Models[0].Name = "Palma"; 那样进行修改
  • 好吧,你可以从你的初始 VM 派生一个 WinformsVM,它会在你的主 VM 的 ReactiveList 上创建一堆 CreateDerviedBindingLists(),这样你就可以在平台之间保持逻辑共享。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 2023-04-01
  • 2017-04-07
  • 2023-03-18
  • 1970-01-01
  • 2018-02-19
相关资源
最近更新 更多