2016-10-04 88 views
2

我已經將流行的UI庫MahappsAvalon.Wizard控件集成在一起。Mahapps 1.3對話框和Avalon.Wizard

它很好地集成在一起,但我遇到了Mahapps對話框的問題。 Wizard控件定義了一個InitializeCommand來處理在嚮導頁面上的輸入。

顯然InitializeCommand在附加到視圖的依賴屬性被初始化之前觸發(DialogParticipation.Register)。

這會導致以下錯誤:

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

重現此問題,請here的樣本項目。

有關如何解決此問題的任何建議?

+1

頁面的XAML是尚未在InitializeCommand創建的,所以你不能使用DialogCoordinator顯示一個對話框。我在您的示例中創建了一個PullRequest,並使用一個將在Xaml的Loaded事件中執行的自定義界面。 – punker76

回答

3

頁面Xaml不是在initialize命令中創建的,所以此時不​​能使用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); }; 
    } 
} 

希望這有助於。

enter image description here

enter image description here

+0

它的工作原理!謝謝你:) – dna2

+0

也爲我工作。另外,我需要按照[這裏](https://msdn.microsoft.com/en-us/magazine/dd419663.aspx)中所述定義'RelayCommand',並且必須將'LastPageViewModel _lastPageViewModel = new LastPageViewModel();'分配給在使用'DialogParticipation.SetRegister'之前的'DataContext'。 –