我们一直试图让ToProperty正常工作,但是遇到了ThrownExceptions没有捕捉到的异常。
我们的测试视图模型如下所示:
public class ViewModel : ReactiveObject, ISupportsActivation
{
private readonly ViewModelActivator _activator = new ViewModelActivator();
public ViewModelActivator Activator
{
get { return _activator; }
}
private ObservableAsPropertyHelper<String> _output;
public string Output
{
get { return _output.Value; }
}
public ViewModel()
{
this.WhenActivated(delegate(Action<IDisposable> action)
{
action(
Run()
.ToObservable()
.ToProperty(this, vm => vm.Output, out _output, "INIT", RxApp.MainThreadScheduler)
.ThrownExceptions.Subscribe(ex => Debug.WriteLine("Exception {0}", ex.Message)));
});
}
public async Task<string> Run()
{
Debug.WriteLine("Running : Begin");
await Task.Delay(5000);
throw new InvalidOperationException("no way hosay");
Debug.WriteLine("Running : End");
return "Assigned";
}
}我们有些简单的视图看起来
public sealed partial class MainPage : Page,IViewFor<ViewModel>
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
this.WhenActivated(d =>
{
d(this.OneWayBind(ViewModel, vm => vm.Output, v => v.Text.Text));
});
}
object IViewFor.ViewModel
{
get { return ViewModel; }
set { ViewModel = (ViewModel)value; }
}
public ViewModel ViewModel
{
get { return (ViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register("ViewModel", typeof(ViewModel), typeof(MainPage), new PropertyMetadata(null));
private void BindButton_OnClick(object sender, RoutedEventArgs e)
{
this.ViewModel = new ViewModel();
}
}现在,如果他快速地连续几次点击“BindButton”,我们就会得到一个ThrownExceptions没有捕捉到的异常。
为什么会这样呢?
此外,关于ToProperty使用的指导是什么?
例如,在WhenActivated中没有绑定会导致输出属性的get属性出现异常,因为_output有一个空值。考虑到可能需要长时间运行的任务来填充ToProperty值,那么应该遵循哪种典型的结构?
编辑:
通过对视图模型进行这种修改,我们现在有了一种情况,就是我们似乎总是困住了例外,为什么会这样?
var exec = Run().ToObservable();
_output = exec.ToProperty(this, x => x.Output, "INIT", RxApp.MainThreadScheduler);
_output.ThrownExceptions.Subscribe(ex => Debug.WriteLine("Exception {0}", ex.Message));发布于 2015-03-14 17:12:53
您看到这些异常的原因是您在ViewModel中使用了ViewModel,而这些VM在任务完成之前就被删除了。您不需要在WhenActivated中使用ViewModel,除非:
ListBoxItemViewModel的MessageBus)。但是老实说,与其每次单击按钮时都创建一个新的ViewModel,不如在视图的构造函数中创建一个ViewModel,然后将该按钮绑定到一个ReactiveCommand。
https://stackoverflow.com/questions/29015861
复制相似问题