使用WPF简单对话框
定义对话框模板SampleMessageDialog.xaml

<UserControl x:Class=”test.SampleMessageDialog”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″
xmlns:materialDesign=”http://materialdesigninxaml.net/winfx/xaml/themes”
mc:Ignorable=”d” d:DesignHeight=”300″ d:DesignWidth=”300″ MaxWidth=”400″>
<Grid Margin=”16″>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock x:Name=”Message” Margin=”0 6 0 0″ FontSize=”18″ Grid.Row=”0″ />
<Button Grid.Row=”1″ IsDefault=”True” Style=”{DynamicResource MaterialDesignFlatButton}” HorizontalAlignment=”Right” Margin=”16 16 16 0″ Command=”{x:Static materialDesign:DialogHost.CloseDialogCommand}”>
ACCEPT
</Button>
</Grid>
</UserControl>
System.InvalidOperationException:“No loaded DialogHost instances.”
 
对应的SampleMessageDialog.cs

using System.Windows.Controls;

namespace test
{
/// <summary>
/// Interaction logic for SampleMessageDialog.xaml
/// </summary>
public partial class SampleMessageDialog : UserControl
{
public SampleMessageDialog()
{
InitializeComponent();
}
}
}
 
对应的函数

public async void MessageTips(string message, object sender, RoutedEventArgs e)
{
var sampleMessageDialog = new SampleMessageDialog
{
Message = { Text = message }
};
await DialogHost.Show(sampleMessageDialog, “RootDialog”);
}
 
在需要的位置使用

MessageTips(“请确认”, sender, e);
 

直接用,会报错:
System.InvalidOperationException:“No loaded DialogHost instances.”
原因是对话框放置的位置找不到,这个放置的位置就是这里的 RootDialog

await DialogHost.Show(sampleMessageDialog, “RootDialog”);
 
需要在windows.xaml里设置,把GRID内容放入到如下容器里面

<materialDesign:DialogHost Identifier=”RootDialog”>
……
</materialDesign:DialogHost>
 
爬了一整天。

————————————————
版权声明:本文为CSDN博主「bondw」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/bondw/article/details/102762482