我正在尝试使用以下代码作为一种安全的方法,以按照this帖子中的建议从我的viewmodel的构造函数中调用异步服务。问题是,this.WhenActivated主体内部什么都没有触发过,为什么有什么主意?

这是我的代码:

class MainViewModel : ReactiveObject, ISupportsActivation, IMainViewModel
{
    private IDataService _dataService;

    private Part _part;

    public Part MyPart
    {
        get { return _part; }
        set { this.RaiseAndSetIfChanged(ref _part, value); }
    }

    public MainViewModel(IDataService dataService)
    {
        _dataService = dataService;

        this.WhenActivated(disposables =>
        {
            _dataService.GetPart("9176900515")
                .ToObservable()
                .Subscribe(
                    result => { MyPart = result; },
                    exception => { LogMe.Log<string>(exception.Message); }
                )
                .DisposeWith(disposables);
        });
    }

    private readonly ViewModelActivator activator = new ViewModelActivator();
    ViewModelActivator ISupportsActivation.Activator
    {
        get { return activator; }
    }

}

最佳答案

为了使WhenActivated在 View 模型内工作,该 View 模型必须是实现ViewModel的 View 的IViewFor<MainViewModel>

然后, View 的MainViewModel将调用WhenActivatedWhenActvated

更新:

这是在WPF中完成的,但所有平台(WPF,UWP,Xamarin)都支持它。

该 View 实现IViewFor<TViewModel>。通过最佳实践,ViewModel属性是DependencyProperty(或Xam.Forms中的BindableProperty)。

public partial class MainWindow : Window, IViewFor<MainViewModel>
{
    public MainWindow()
    {
        InitializeComponent();

        this.WhenActivated(d =>
        {
        // This will be called
    });
    }

    public MainViewModel ViewModel
    {
        get => (MainViewModel)GetValue(ViewModelProperty);
        set => SetValue(ViewModelProperty, value);
    }
    public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(nameof(ViewModel), typeof(MainViewModel), typeof(MainWindow), new PropertyMetadata(null));

    object IViewFor.ViewModel
    {
        get => ViewModel;
        set => ViewModel = value as MainViewModel;
    }
}

现在,在 View 中调用WhenActivated时,将在VM中调用WhenActivated
class MainViewModel : ReactiveObject, ISupportsActivation
{
    public ViewModelActivator Activator => _activator;
    private ViewModelActivator _activator = new ViewModelActivator();

    public MainViewModel()
    {
        this.WhenActivated(d =>
        {
            // This will be called
        });
    }
}

关于c# - ReactiveUI激活时不触发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44331655/

10-11 20:15