我也找不到任何关于如何在 WPF 中使用 ReactiveUI 打开新窗口的示例。
我最终做的是向我的视图添加一个依赖属性(因为你不能将参数传递给视图构造函数)。例如,如果您需要将字符串值 userName 传递到新窗口,则必须将以下依赖项属性添加到该视图类:
public static readonly DependencyProperty UserNameProperty =
DependencyProperty.Register("UserName", typeof(string), typeof(YourView),
new PropertyMetadata(default(string)));
public string UserName
{
get => (string) GetValue(UserNameProperty);
set => SetValue(UserNameProperty, value);
}
然后,在创建视图时,您可以为该属性分配一个值。在你的情况下:
Window window = Locator.Current.GetService("WindowToOpen") as Window;
window.PropertyToChange = valueOfProperty;
window.Show();
如果您需要视图模型中的属性值(如果您使用 MVVM,您可能会这样做),请将依赖项属性绑定到视图模型中的属性。这必须在视图的WhenActivated 方法中完成:
this.WhenActivated(disposables =>
{
// Instantiate the view model just in case it is null
ViewModel ??= Locator.Current.GetService<YourView>() ??
throw new InvalidOperationException("YourViewis not registered.");
this.WhenAnyValue(view => view.UserName)
.BindTo(ViewModel, viewModel => viewModel.UserName)
.DisposeWith(disposables);
// other bindings
});
我知道这一切都让人感觉非常笨拙和凌乱。但我还没有找到任何关于如何仅使用 ReactiveUI 正确执行此操作的示例。