lepoco/wpfui · error · InvalidOperationException

Cannot change DialogHost while the dialog is being shown.

Error message

Cannot change DialogHost while the dialog is being shown.

What it means

Thrown by the DialogHost setter when attempting to change the host while the dialog is currently being shown (IsShowing is true). Changing the rendering host mid-display would corrupt the visual tree/focus state, so the setter blocks the mutation.

Source

Thrown at src/Wpf.Ui/Controls/ContentDialog/ContentDialog.cs:633

    /// <exception cref="InvalidOperationException">
    /// Thrown if trying to set DialogHost when DialogHostEx is already set, or if trying to change DialogHost while the dialog is being shown.
    /// </exception>
    [Obsolete("DialogHost is deprecated. Please use DialogHostEx instead.")]
    public ContentPresenter? DialogHost
    {
        get => _dialogHost;
        set
        {
            if (_dialogHostEx is not null)
            {
                throw new InvalidOperationException(
                    "Cannot set DialogHost when DialogHostEx is already set."
                );
            }

            if (IsShowing)
            {
                throw new InvalidOperationException(
                    "Cannot change DialogHost while the dialog is being shown."
                );
            }

            if (ReferenceEquals(_dialogHost, value))
            {
                return;
            }

            if (_dialogHost is not null)
            {
                ContentDialogHostBehavior.SetIsEnabled(_dialogHost, false);
            }

            _dialogHost = value;

            if (_dialogHost is not null)
            {

View on GitHub (pinned to ffebacd610)

Solutions

  1. Wait for the dialog to close (await ShowAsync to completion) before changing DialogHost/DialogHostEx.
  2. Create a new ContentDialog instance for a different host rather than mutating the host of one already showing.
  3. Gate the assignment on !dialog.IsShowing before setting.

Example fix

// before
dialog.DialogHost = newHost; // while ShowAsync is running

// after
await dialog.ShowAsync();
dialog.DialogHost = newHost; // safe, IsShowing is false
Defensive patterns

Strategy: validation

Validate before calling

if (!dialog.IsShowing) { dialog.DialogHost = newHost; }

Type guard

static bool CanChangeHost(ContentDialog d) => !d.IsShowing;

Prevention

When it happens

Trigger: Reassigning ContentDialog.DialogHost (or, symmetrically, DialogHostEx) while ShowAsync is in progress and IsShowing is true. The guard fires before the actual assignment.

Common situations: Code that swaps hosts in response to navigation/events that occur during a dialog's display, or reusing a dialog and trying to re-point it before the previous ShowAsync completed/closed.

Related errors


AI-assisted analysis of lepoco/wpfui@ffebacd610 (2026-08-13). Data as JSON: /api/errors/9a668d3d16aa93df. Report an issue: GitHub.