如何使用ReactiveList,以便在添加/删除/修改项目时更新UI

时间:2017-10-03 21:59:48

标签: winforms reactiveui

我正在使用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?

1 个答案:

答案 0 :(得分:1)

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