gpt4 book ai didi

c# - 如何在 AvaloniaUI(测试版)中显示消息框

转载 作者:太空宇宙 更新时间:2023-11-03 22:34:56 27 4
gpt4 key购买 nike

我正在玩 Avalonia我正在尝试显示一个消息框,该消息框等同于 WinForms 的 MessageBox.Show()。我找到了 GitHub issue那是为此请求一个 API,但我想知道人们在此期间在做什么。

我们是否需要实现一个像消息框一样的窗口或用户控件并通过 ShowDialog 显示它?

最佳答案

消息框.xaml

<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="MsgBox.MessageBox" SizeToContent="WidthAndHeight" CanResize="False">
<StackPanel HorizontalAlignment="Center">
<TextBlock HorizontalAlignment="Center" Name="Text"/>
<StackPanel HorizontalAlignment="Center" Orientation="Horizontal" Name="Buttons">
<StackPanel.Styles>
<Style Selector="Button">
<Setter Property="Margin" Value="5"/>
</Style>
</StackPanel.Styles>

</StackPanel>
</StackPanel>
</Window>

MessageBox.xaml.cs

using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;

namespace MsgBox
{
class MessageBox : Window
{
public enum MessageBoxButtons
{
Ok,
OkCancel,
YesNo,
YesNoCancel
}

public enum MessageBoxResult
{
Ok,
Cancel,
Yes,
No
}

public MessageBox()
{
AvaloniaXamlLoader.Load(this);
}

public static Task<MessageBoxResult> Show(Window parent, string text, string title, MessageBoxButtons buttons)
{
var msgbox = new MessageBox()
{
Title = title
};
msgbox.FindControl<TextBlock>("Text").Text = text;
var buttonPanel = msgbox.FindControl<StackPanel>("Buttons");

var res = MessageBoxResult.Ok;

void AddButton(string caption, MessageBoxResult r, bool def = false)
{
var btn = new Button {Content = caption};
btn.Click += (_, __) => {
res = r;
msgbox.Close();
};
buttonPanel.Children.Add(btn);
if (def)
res = r;
}

if (buttons == MessageBoxButtons.Ok || buttons == MessageBoxButtons.OkCancel)
AddButton("Ok", MessageBoxResult.Ok, true);
if (buttons == MessageBoxButtons.YesNo || buttons == MessageBoxButtons.YesNoCancel)
{
AddButton("Yes", MessageBoxResult.Yes);
AddButton("No", MessageBoxResult.No, true);
}

if (buttons == MessageBoxButtons.OkCancel || buttons == MessageBoxButtons.YesNoCancel)
AddButton("Cancel", MessageBoxResult.Cancel, true);


var tcs = new TaskCompletionSource<MessageBoxResult>();
msgbox.Closed += delegate { tcs.TrySetResult(res); };
if (parent != null)
msgbox.ShowDialog(parent);
else msgbox.Show();
return tcs.Task;
}


}

}

用法:

await  MessageBox.Show(mainWindow, "Test", "Test title", MessageBox.MessageBoxButtons.YesNoCancel)

关于c# - 如何在 AvaloniaUI(测试版)中显示消息框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55706291/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com