【问题标题】:How to use ReactiveUI Command in MvvmCross WPF?如何在 MvvmCross WPF 中使用 ReactiveUI 命令?
【发布时间】:2020-04-17 23:35:35
【问题描述】:

我赞成 ReactiveUI 中的命令绑定,并希望集成到我当前基于 MvvmCross 的项目中。

我已按照数据绑定 - WPF 中的教程进行操作。我只是用 IViewFor 修改 View,而不是 ReactiveObject VIewModel,因为它继承了 MvvmCross 对象。

当我将命令与基本集绑定时,一切正常 - 比如 ReactiveCommand.Create(TestCommand)。 但是当我尝试使用其中一个有利的功能时,可以执行(Create(command,canExecute),它不起作用:(

看来 ViewModel = new TheViewModel();在本教程中,只需创建另一个 ViewModel 实例进行交互。并且我的 MvvmCross 中的任何属性更改都不会反映在 View 中创建的 ViewModel。

那么如何在 MvvmCross WPF 中正确使用 ReactiveUI 命令呢?

【问题讨论】:

  • 你用什么来生成你的 CanExecute?
  • @GlennWatson ,我找到了解决方案。顺便说一句,我使用 this.WhenAnyValue 来生成 canExecute。实际上,教程中有错误:reactiveui.net/docs/handbook/data-binding/…。如果想与 MvvmCross 集成,我们可以直接使用 ReactiveCommand 而无需修改 VIew。总之,1.在View中使用MvvmCross提供的数据绑定; 2.在ViewModel中使用ReactiveUI命令

标签: mvvmcross reactiveui


【解决方案1】:

说明

我已经想出了解决方案并在此处发布以防有人遇到此类问题。

教程:https://reactiveui.net/docs/handbook/data-binding/windows-presentation-foundation 更多关于如何在 WPF 中使用 ReactiveUI 绑定,我不确定在使用 ReactiveUI 时这样做是否正确,因为它创建了 ViewModel 的新实例。至少,这不适用于 MvvmCross。

要在 MvvmCross 中使用 ReactiveUI Command,我们可以在 ViewModel 中创建 ReactiveCommand,并使用 MvvmCross-way 来绑定命令。

基于 MvvmCross 和 ReactiveCommand 的 ViewModel

// ViewModel code like this:

public ReactiveCommand<Unit, Unit> DoSomethingCommand { get; }

public SomeViewModelConstructor(){
    var canExecuteDoSomethingCommand = this.WhenAnyValue(/* value condition stuff here */);
    DoSomethingCommand = ReactiveCommand.CreateFromTask(DoSomething, canExecuteDoSomethingCommand);
}

async Task DoSomehing(){
    await SomeService.DoSomething();
}

基于 MvvmCross 和 Fluent Binding(类型安全)的视图

// Type-safe View code like this:

// in xaml
<Button Content="DoSomething" x:Name="ButtonDoSomething" />

// in xaml.cs
public SomeViewConstructor(){
    // type-safe binding
    using var set = this.CreateBindingSet<SomeView, SomeViewModel>();
    set.Bind(ButtonDoSomething)
        .For(v => v.Command)
        .To(vm => vm.DoSomethingCommand);
}

【讨论】:

    猜你喜欢
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多