在取消对话框后重置



我刚刚开始探索Catel,我真的很喜欢它。

但是现在我被卡住了,因为我找不到以下不工作的原因。我创建了一个Foo模型,一个FooViewModel和一个FooWindowViewModel。我使用FooViewModel来显示Foo模型的状态,并使用FooWindowViewModel来显示一个对话框来编辑它。

我的问题是,当我在对话框中按取消键时,我所做的更改不会恢复。

简短的旁注:在示例项目(https://docs.catelproject.com/5.12/getting-started/wpf/)中,重置行为是我所期望的。

你可以在这里找到一些示例代码:模型:

using Catel.Data;
using System;
using System.Collections.Generic;
using System.Text;
namespace My1stCatelProject.Models
{
public class Foo : ModelBase
{
public string TextProp { get; set; }
}
}
public class FooWindowViewModel : ViewModelBase
{
public FooWindowViewModel(Foo model)
{
Model = model;
}
public override string Title { get => "FooWindow"; protected set => base.Title = value; }
[Model]
public Foo Model { get; set; }
[ViewModelToModel(nameof(Model))]
public string TextProp { get; set; }
}
using Catel.Data;
using Catel.IoC;
using Catel.MVVM;
using Catel.Services;
using My1stCatelProject.Models;
using System.ComponentModel;
using System.Threading.Tasks;
using Catel;
namespace My1stCatelProject.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
private readonly IUIVisualizerService _uiVisualizerService;
public MainWindowViewModel(IUIVisualizerService uiVisualizerService)
{
_uiVisualizerService = uiVisualizerService;
EditCommand = new TaskCommand(OnEdit);
}
public override string Title { get { return "Welcome to My1stCatelProject"; } }
public Foo MyFoo
{
get { return GetValue<Foo>(MyFooProperty); }
set { SetValue(MyFooProperty, value); }
}
public static readonly PropertyData MyFooProperty = RegisterProperty(nameof(MyFoo), typeof(Foo), () => new Foo() { TextProp = "XY" });
// TODO: Register models with the vmpropmodel codesnippet
// TODO: Register view model properties with the vmprop or vmpropviewmodeltomodel codesnippets
// TODO: Register commands with the vmcommand or vmcommandwithcanexecute codesnippets
protected override async Task InitializeAsync()
{
await base.InitializeAsync();
// TODO: subscribe to events here
}
protected override async Task CloseAsync()
{
// TODO: unsubscribe from events here
await base.CloseAsync();
}
public TaskCommand EditCommand { get; set; }
private async Task OnEdit()
{
var typeFactory = this.GetTypeFactory();
var fooWindowViewModel = typeFactory.CreateInstanceWithParametersAndAutoCompletion<FooWindowViewModel>(MyFoo);
if (await _uiVisualizerService.ShowDialogAsync(fooWindowViewModel) ?? false)
{
;
} else
{
// ((IEditableObject)fooWindowViewModel).CancelEdit(); // Doesnt work either
}
}
}
}

谢谢!

编辑1:如果我在模型和视图模型中的beginEdit和cancelEdit EventHandler中插入断点,我可以看到cancelEdit永远不会执行。

要重现意外的行为,你可以使用到存储库的链接:https://github.com/Stjefan/My1stCatelProject

Edit 2:在结束应用程序时执行CancelEdit。我猜,我在初始化中搞砸了什么

我认为该窗口也决定使用FooViewModel作为视图模型。您可以通过在构造函数中放置一个断点来测试这一点,看看它是否真的被调用了。

如果没有,那么您可以/应该手动为窗口注册正确的视图模型(因为由于命名约定的设置,FooViewModel将比FooWindowViewModel更早被解析)。

uiVisualizerService.Register<FooWindowViewModel, FooWindow>();

请注意,如果您愿意,可以对窗口和控件使用相同的vm。然后,用户控件将重用父虚拟机(在本例中是窗口虚拟机),但您是否想要最终取决于您。

最新更新