lepoco/wpfui · error · InvalidOperationException

Cannot set DialogHostEx when DialogHost is already set.

Error message

Cannot set DialogHostEx when DialogHost is already set.

What it means

Thrown by the DialogHostEx setter when the legacy DialogHost is already set on the same ContentDialog. It is the symmetric guard to error 17: once a ContentPresenter host is assigned, setting the new ContentDialogHost on that dialog is rejected to avoid mixed hosting.

Source

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

            UpdateIsLegacyHost();
        }
    }

    /// <summary>
    /// Gets or sets <see cref="DialogHostEx"/> inside of which the dialogue will be placed.
    /// </summary>
    /// <exception cref="InvalidOperationException">
    /// Thrown if trying to set DialogHostEx when DialogHost is already set, or if trying to change DialogHostEx while the dialog is being shown.
    /// </exception>
    public ContentDialogHost? DialogHostEx
    {
        get => _dialogHostEx;
        set
        {
            if (_dialogHost is not null)
            {
                throw new InvalidOperationException(
                    "Cannot set DialogHostEx when DialogHost is already set."
                );
            }

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

            if (!ReferenceEquals(_dialogHostEx, value))
            {
                _dialogHostEx = value;
            }

            UpdateIsLegacyHost();
        }

View on GitHub (pinned to ffebacd610)

Solutions

  1. Remove the legacy DialogHost assignment/binding and use DialogHostEx exclusively.
  2. Audit XAML for DialogHost= bindings (CS0618) and convert them to DialogHostEx.
  3. Ensure a single host assignment strategy per dialog across both XAML and code-behind.

Example fix

// before
<ui:ContentDialog DialogHost="{Binding ElementName=MyPresenter}" />
... 
dialog.DialogHostEx = myHost; // throws, DialogHost already set

// after
<ui:ContentDialog DialogHostEx="{Binding ElementName=MyDialogHost}" />
Defensive patterns

Strategy: validation

Validate before calling

if (dialog.DialogHost is null) { dialog.DialogHostEx = host; }

Type guard

static bool CanSetHostEx(ContentDialog d) => d.DialogHost is null && !d.IsShowing;

Prevention

When it happens

Trigger: Assigning ContentDialog.DialogHostEx = someHost after ContentDialog.DialogHost was already assigned (or bound in XAML). The _dialogHost field is non-null at set time, triggering the throw.

Common situations: XAML that still binds the obsolete DialogHost property plus code that sets DialogHostEx, or migration where the old binding was not removed before introducing the new host.

Related errors


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