【发布时间】:2017-12-06 18:09:09
【问题描述】:
我有一个窗口,它使用 ReactiveUI 交互打开第二个窗口作为模式对话框,然后从第二个窗口中的 ListBox 返回数据。
问题是当 .ShowDialog() 完成时,ViewModel 的 SelectedItem 总是计算为 null。我已经确认绑定工作正常,并且所选项目在对话框窗口的 ViewModel 中得到正确更新。只有当我返回到交互时,该属性才会重置为其默认值(null)。
我在这里整理了一个最小的问题示例:
https://github.com/replicaJunction/ReactiveDialogTest
主要被测逻辑在MainWindowViewModel.cs中。
编辑:这是代码中的一个 sn-p 基本思想:
GetNumberFromDialog = new Interaction<Unit, int>();
GetNumberFromDialog.RegisterHandler(interaction =>
{
var vm = new DialogWindowViewModel();
// Get a reference to the view for this VM
var view = Locator.Current.GetService<IViewFor<DialogWindowViewModel>>();
// Set its VM to our current reference
view.ViewModel = vm;
var window = view as Window;
var dialogResult = window.ShowDialog();
// At this point, vm.SelectedNumber is expected be the number the user selected -
// but instead, it always evaluates to 0.
if (true == dialogResult)
interaction.SetOutput(vm.SelectedNumber);
else
interaction.SetOutput(-1);
});
OpenDialog = ReactiveCommand.Create(() =>
{
GetNumberFromDialog.Handle(Unit.Default)
.Where(retVal => -1 != retVal) // If the dialog did not return true, don't update
.Subscribe(retVal =>
{
this.MyNumber = retVal;
});
});
重现问题的步骤:
- 运行项目。请注意带有 -5000 的标签 - 这是要更新的数字。
- 单击“打开对话框”按钮。将打开一个对话窗口。
- 在列表框中选择一个数字。请注意,“当前选择”下的标签会更新 - 这与 ListBox.SelectedItem 绑定到相同的值。
- 单击确定。对话框关闭。
预期行为:主窗口中“我的号码是”下方的标签应更新为您在 ListBox 中选择的值。
实际行为:标签更新为 0(int 的默认值)。
为什么我的 ViewModel 在对话框关闭时会自行重置?
【问题讨论】:
标签: c# wpf mvvm reactiveui