自定义messagebox_使用自定义MessageBox的AvaloniaUI功能
时间: 2023-12-10 11:05:35 浏览: 100
可以使用AvaloniaUI中的Dialogs类来创建自定义的MessageBox。以下是一个示例:
```csharp
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia;
using Avalonia.Interactivity;
using Avalonia.Threading;
public class CustomMessageBox : Window
{
public CustomMessageBox()
{
this.InitializeComponent();
this.DataContext = this;
}
public static async Task<MessageBoxResult> Show(string message, string title, MessageBoxButton buttons)
{
var msgBox = new CustomMessageBox();
msgBox.Message = message;
msgBox.Title = title;
msgBox.Buttons = buttons;
var result = await msgBox.ShowDialog<MessageBoxResult>();
return result;
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
public string Message { get; set; }
public string Title { get; set; }
public MessageBoxButton Buttons { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
var result = button.Content.ToString().ToLower();
this.Close(result == "ok" ? MessageBoxResult.OK : MessageBoxResult.Cancel);
}
}
```
然后在XAML文件中定义MessageBox的布局:
```xaml
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="CustomMessageBox"
Width="300"
Height="150"
WindowStartupLocation="CenterScreen"
ShowInTaskbar="False"
Topmost="True"
CanResize="False"
Title="{Binding Title}">
<StackPanel>
<TextBlock Text="{Binding Message}" Margin="10,10,10,20"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,0,10,10">
<Button Content="OK" Margin="0,0,10,0" Click="Button_Click"/>
<Button Content="Cancel" Click="Button_Click"/>
</StackPanel>
</StackPanel>
</Window>
```
最后,在代码中调用CustomMessageBox.Show方法来显示MessageBox:
```csharp
var result = await CustomMessageBox.Show("Are you sure you want to delete this file?", "Confirm Delete", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
// Delete the file
}
```
阅读全文