Files
Shrlalgo.RvKits/WPFluent/ContentDialogService.cs
2025-05-05 17:04:06 +08:00

61 lines
2.4 KiB
C#

using System.Windows.Controls;
using WPFluent.Controls;
namespace WPFluent;
/// <summary>
/// Represents a contract with the service that creates <see cref="ContentDialog"/>.
/// </summary>
/// <example>
/// <code lang="xml"> &lt;ContentPresenter x:Name="RootContentDialogPresenter" Grid.Row="0" /&gt;</code> <code
/// lang="csharp"> IContentDialogService contentDialogService = new ContentDialogService();
/// contentDialogService.SetContentPresenter(RootContentDialogPresenter); await _contentDialogService.ShowAsync( new
/// ContentDialog(){ Title = "The cake?", Content = "IS A LIE!", PrimaryButtonText = "Save", SecondaryButtonText =
/// "Don't Save", CloseButtonText = "Cancel" } );</code>
/// </example>
public class ContentDialogService
{
private ContentPresenter? _dialogHost;
/// <summary>
/// 提供对 <see cref="ContentPresenter"/> 的直接访问。
/// </summary>
/// <returns>引用当前选定的 <see cref="ContentPresenter"/> 显示 <see cref="ContentDialog"/> 的内容。</returns>
public ContentPresenter? GetDialogHost() { return _dialogHost; }
/// <summary>
/// Sets the <see cref="ContentPresenter"/>
/// </summary>
/// <param name="dialogHost">
/// <see cref="ContentPresenter"/> inside of which the dialogue will be placed. The new <see cref="ContentDialog"/> will
/// replace the current <see cref="ContentPresenter.Content"/>.
/// </param>
public void SetDialogHost(ContentPresenter contentPresenter) { _dialogHost = contentPresenter; }
/// <summary>
/// Asynchronously shows the specified dialog.
/// </summary>
/// <param name="dialog">The dialog to be displayed.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
/// <returns>A task that represents the asynchronous operation. The task result contains the dialog result.</returns>
public Task<ContentDialogResult> ShowAsync(ContentDialog dialog, CancellationToken cancellationToken)
{
if (_dialogHost == null)
{
throw new InvalidOperationException("The DialogHost was never set.");
}
if (dialog.DialogHost != null && _dialogHost != dialog.DialogHost)
{
throw new InvalidOperationException("The DialogHost is not the same as the one that was previously set.");
}
dialog.DialogHost = _dialogHost;
return dialog.ShowAsync(cancellationToken);
}
}