WPF Trying to create a library with custom window control but I get an Error: Cannot change AllowsTransparency after a Window has been shown

WPF Trying to create a library with custom window control but I get an Error: Cannot change AllowsTransparency after a Window has been shown

我想创建一个自定义控件模板(在 library/separate 程序集上)并基于该自定义控件模板启动一个 dialog/message 框,而不需要单独的客户端 XAML 基于该自定义控件模板。

控件模板开发如下...

控制模板Class

public class DialogWindow : Window
{
    #region Constructors
    static DialogWindow()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(DialogWindow),
            new FrameworkPropertyMetadata(typeof(DialogWindow)));
    }

    public DialogWindow()
    {
    }

    public DialogWindow(string title, string header, string message)
    {
        Title = title;
        HeaderText = header;
        MessageText = message;
    }
        ///...
        ///the rest of the custom control class
        ///...

控件模板样式

    <Style TargetType="{x:Type customcontrols:DialogWindow}">

        <Setter Property="WindowStyle" Value="None" />
        <Setter Property="AllowsTransparency" Value="True" />
        <Setter Property="ResizeMode" Value="NoResize"/>
        ...
        <!-- the rest of the control template-->
        ...
    </Style>

在客户端应用程序上,我想将控件模板用作。非常像 MessageBox 类型声明,但完全是从头开始设计的。

客户代码

        CustomControls.DialogWindow custom = new CustomControls.DialogWindow("Sample Title", "Sample Header", 
            Properties.Resources.DocumentResourceSample);
        custom.IsOKEnabled = true;
        custom.OKButtonClick += CloseDialog;
        custom.ShowDialog();

我在尝试启动对话框 window 时遇到的完整错误是

Error: Cannot change AllowsTransparency after a Window has been shown or WindowInteropHelper.EnsureHandle has been called.

我真的很想通过自定义控件模板样式设置AllowsTransparency,否则会出现粗黑边。

你们认为我在这里遗漏了什么?

如果你们有兴趣,下面是我设法解决这个问题的方法。 我创建了一个实现自定义对话框 window 控件的用户控件

代码

    public partial class CustomDialogBox : DialogWindow
    {
    public CustomDialogBox()
    {
        InitializeComponent();
    }

还连接了所有自定义内容

    public CustomDialogBox(string title, string header, string message)
    {
        Title = title;
        HeaderText = header;
        MessageText = message;

        InitializeComponent();
    }

XAML

<customcontrols:DialogWindow 
    Style="{StaticResource {x:Type customcontrols:DialogWindow}}"
    >
     <Grid>
     </Grid>
</customcontrols:DialogWindow>

一切似乎都运行良好。 我认为这不是一个很好的实现。如果有更好的方法,我仍然很感兴趣。

对于在尝试制作自定义 window class 并使用 WPF 样式设置样式时偶然发现这种情况的任何人,我已经想出了一个很好的解决方案来解决这个问题而不用费力Window class.

内的代码 AllowTrasparency

我已经在此处记录并分享了代码:https://gist.github.com/aurimasniekis/53533fddefe95b04bcad37b815197b8e

P.S。这不能解决在运行时更改 AllowTrasparency,但允许您在 Window 创建时使用样式来控制它。