Mahapps 1.3 对话框和 Avalon.Wizard

Mahapps 1.3 dialogs and Avalon.Wizard

我集成了流行的 UI 库 Mahapps with the Avalon.Wizard 控件。

它集成得很好,但我对 Mahapps 对话框有疑问。向导控件定义了一个 InitializeCommand 来处理向导页面上的输入。

显然,InitializeCommand 在附加到视图的依赖项 属性 初始化 (DialogParticipation.Register) 之前被触发。

这会导致以下错误:

Context is not registered. Consider using DialogParticipation.Register in XAML to bind in the DataContext.

重现该问题的示例项目可用here

关于如何解决这个问题有什么建议吗?

页面 Xaml 不是在初始化命令中创建的,所以此时您不能使用 DialogCoordinator。

这是一个带有 LoadedCommand 的自定义接口,您可以在 ViewModel 中实现它并在后面的 Xaml 代码中调用它。

public interface IWizardPageLoadableViewModel
{
    ICommand LoadedCommand { get; set; }
}

视图模型:

public class LastPageViewModel : WizardPageViewModelBase, IWizardPageLoadableViewModel
{
    public LastPageViewModel()
    {
        Header = "Last Page";
        Subtitle = "This is a test project for Mahapps and Avalon.Wizard";

        InitializeCommand = new RelayCommand<object>(ExecuteInitialize);
        LoadedCommand = new RelayCommand<object>(ExecuteLoaded);
    }

    public ICommand LoadedCommand { get; set; }

    private async void ExecuteInitialize(object parameter)
    {
        // The Xaml is not created here! so you can't use the DialogCoordinator here.
    }

    private async void ExecuteLoaded(object parameter)
    {
        var dialog = DialogCoordinator.Instance;
        var settings = new MetroDialogSettings()
        {
            ColorScheme = MetroDialogColorScheme.Accented
        };
        await dialog.ShowMessageAsync(this, "Hello World", "This dialog is triggered from Avalon.Wizard LoadedCommand", MessageDialogStyle.Affirmative, settings);
    }
}

和视图:

public partial class LastPageView : UserControl
{
    public LastPageView()
    {
        InitializeComponent();
        this.Loaded += (sender, args) =>
        {
            DialogParticipation.SetRegister(this, this.DataContext);
            ((IWizardPageLoadableViewModel) this.DataContext).LoadedCommand.Execute(this);
        };
        // if using DialogParticipation on Windows which open / close frequently you will get a
        // memory leak unless you unregister.  The easiest way to do this is in your Closing/ Unloaded
        // event, as so:
        //
        // DialogParticipation.SetRegister(this, null);
        this.Unloaded += (sender, args) => { DialogParticipation.SetRegister(this, null); };
    }
}

希望对您有所帮助。