2016-10-04 4 views
2

Я интегрировал популярную библиотеку UI Mahapps с элементом управления Avalon.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 в вашем примере с помощью специального интерфейса, который будет выполнен в событии Loaded Xaml. – punker76

ответ

3

Страница Xaml не создается при инициализации, поэтому вы не можете использовать DialogCoordinator в этой точке.

Вот пользовательский интерфейс с LoadedCommand, который можно реализовать в ViewModel и вызвать его по коду Xaml.

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

The ViewModel:

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

работал и на меня. Кроме того, мне нужно было определить «RelayCommand», как описано [здесь] (https://msdn.microsoft.com/en-us/magazine/dd419663.aspx), и ему пришлось назначить 'LastPageViewModel _lastPageViewModel = новый LastPageViewModel();' to 'DataContext' перед использованием' DialogParticipation.SetRegister'. –

Смежные вопросы