-_._- 2024-02-09 13:38 采纳率: 25%
浏览 13

WPF自定义弹窗闪退

问题

这个摇号软件的C# WPF代码可以通过编译,但是在使用Display()的第一个重载时程序会闪退,如何使自定义弹窗MyMessageBox正常显示?

代码

// MyMessageBox.xaml.cs

using Microsoft.Win32;
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Lottery
{
    /// <summary>
    /// Interaction logic for MyMessageBox.xaml
    /// </summary>
    public enum MyMessageBoxStyles
    {
        Information,
        Warning,
        Error
    }
    
    public partial class MyMessageBox : Window
    {
        private readonly Button conb = new Button
        {
            Margin = new Thickness(3),
            Content = "Continue",
            Style = (Style)Application.Current.FindResource("ButtonStyle")
        };
        
        private void Set(Brush start, Brush mid, Brush end)
        {
            Ani.ButtonBind(b, start, mid, end);
            Ani.ButtonBind(c, start, mid, end);
            Ani.ButtonBind(sb, start, mid, end);
        }

        private void SetMore(Brush start, Brush mid, Brush end)
        {
            Set(start, mid, end);
            Ani.ButtonBind(conb, start, mid, end);
        }

        private void Register(string title, string content, Window owner, bool co, MyMessageBoxStyles style)
        {
            InitializeComponent();
            cb.ItemsSource = new int[] { 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29 };
            cb.SelectedIndex = 4;
            cb.SelectionChanged += (s, e) => { t.FontSize = int.Parse(cb.SelectedItem.ToString()); };
            b.Click += (s, e) => { Close(); };
            c.Click += (s, e) => { Clipboard.SetText(t.Text); };
            sb.Click += (s, e) =>
            {
                SaveFileDialog dialog = new SaveFileDialog()
                {
                    Title = "Save File",
                    Filter = "Text Files (*.txt)|*.txt"
                };
                if (dialog.ShowDialog() == true)
                {
                    try { File.WriteAllText(dialog.FileName, t.Text); }
                    catch (Exception ex) { Display("Error", $"Error message: {ex.Message}", this, MyMessageBoxStyles.Error); }
                }
            };
            switch (style)
            {
                case MyMessageBoxStyles.Information:
                    if (co) SetMore(Brushes.DeepSkyBlue, Brushes.DodgerBlue, Brushes.CornflowerBlue);
                    else Set(Brushes.DeepSkyBlue, Brushes.DodgerBlue, Brushes.CornflowerBlue);
                    break;
                case MyMessageBoxStyles.Warning:
                    if (co) SetMore(Brushes.Orange, Brushes.DarkOrange, Brushes.Coral);
                    else Set(Brushes.Orange, Brushes.DarkOrange, Brushes.Coral);
                    break;
                case MyMessageBoxStyles.Error:
                    if (co) SetMore(new SolidColorBrush(Color.FromRgb(255, 75, 75)), Brushes.Red, Brushes.Crimson);
                    else Set(new SolidColorBrush(Color.FromRgb(255, 75, 75)), Brushes.Red, Brushes.Crimson);
                    break;
            }
            Title = title;
            Owner = owner;
            t.Text = content;
        }

        public MyMessageBox(string title, string content, Window owner, MyMessageBoxStyles style) { Register(title, content, owner, false, style); }

        public MyMessageBox(string title, string content, Window owner, Action action, MyMessageBoxStyles style)
        {
            conb.Click += (s, e) => {
                Close();
                action();
            };
            RowDefinition newRow = new RowDefinition { Height = new GridLength(36) };
            g.RowDefinitions.Add(newRow);
            Grid.SetRow(conb, 4);
            Grid.SetColumnSpan(conb, 2);
            g.Children.Add(conb);
            MinHeight = 236;
            Register(title, content, owner, true, style);
        }

        public static void Display(string title, string content, Window owner, Action action, MyMessageBoxStyles style = MyMessageBoxStyles.Information)
        {
            MyMessageBox m = new MyMessageBox(title, content, owner, action, style);
            m.ShowDialog();
        }

        public static void Display(string title, string content, Window owner, MyMessageBoxStyles style = MyMessageBoxStyles.Information)
        {
            MyMessageBox m = new MyMessageBox(title, content, owner, style);
            m.ShowDialog();
        }
    }
}
// Ani.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace Lottery
{
    internal class Ani
    {
        public static void ButtonBind(Button b, Brush start, Brush mid, Brush end)
        {
            b.Background = mid;
            b.Foreground = Brushes.White;
            b.MouseEnter += (s, e) => { ScaleAniShow(b, 1, 1.05); b.Background = start; };
            b.MouseLeave += (s, e) => { ScaleAniShow(b, 1.05, 1); b.Background = mid; };
            b.PreviewMouseDown += (s, e) => { ScaleAniShow(b, 1.05, 0.95); b.Background = end; };
            b.PreviewMouseUp += (s, e) => { ScaleAniShow(b, 0.95, 1.05); b.Background = start; };
        }

        public static void TextBoxBind(TextBox t)
        {
            t.PreviewMouseDown += (s, e) => { ScaleAniShow(t, 1, 0.95); };
            t.PreviewMouseUp += (s, e) => { ScaleAniShow(t, 0.95, 1); };
        }

        public static void ScaleAniShow(UIElement element, double Sizefrom, double Sizeto, double RenderX = 0.5, double RenderY = 0.5, int power = 5)
        {
            ScaleTransform scale = new ScaleTransform();
            element.RenderTransform = scale;  // Define the central position of the circle.
            element.RenderTransformOrigin = new Point(RenderX, RenderY);  // Define the transition animation, 'power' is the strength of the transition.
            DoubleAnimation scaleAnimation = new DoubleAnimation()
            {
                From = Sizefrom,  // Start value
                To = Sizeto,  // End value
                FillBehavior = FillBehavior.HoldEnd,
                Duration = TimeSpan.FromMilliseconds(250),  // Animation playback time
                EasingFunction = new PowerEase()  // Ease function
                {
                    EasingMode = EasingMode.EaseInOut,
                    Power = power
                }
            };
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);
        }
    }
}
<Window x:Class="Lottery.MyMessageBox"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        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"
        Height="260" Width="300" MinHeight="200" MinWidth="250" WindowStartupLocation="CenterOwner">
    <Grid Margin="3" Name="g">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="27"/>
            <RowDefinition Height="36"/>
            <RowDefinition Height="36"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <ScrollViewer VerticalScrollBarVisibility="Auto" Grid.Row="0" Margin="3" Grid.ColumnSpan="2">
            <TextBlock Name="t" FontSize="17" TextWrapping="Wrap"/>
        </ScrollViewer>
        <ComboBox Name="cb" IsReadOnly="True" Grid.Row="1" Margin="3" Grid.Column="1" ToolTip="Change the font size of the text above."/>
        <Label Content="Font Size:" FontSize="15" Grid.Row="1" Grid.Column="0" ToolTip="Change the font size of the text above."/>
        <Button Style="{DynamicResource ButtonStyle}" Content="Copy" Name="c" Grid.Row="2" Grid.Column="0" Margin="3"/>
        <Button Style="{DynamicResource ButtonStyle}" Content="Close" Name="b" Grid.Row="2" Grid.Column="1" Margin="3"/>
        <Button Style="{DynamicResource ButtonStyle}" Content="Save" Name="sb" Grid.Row="3" Margin="3" Grid.ColumnSpan="2"/>
    </Grid>
</Window>

VS显示错误在:

img

  • 写回答

3条回答 默认 最新

  • 专家-赤兔[在线] 全栈领域优质创作者 2024-02-09 13:39
    关注

    引自免费微信小程序:皆我百晓生

    在分析问题之前,请确认以下几点以排查可能的闪退原因:

    1. 确保XAML资源文件正确加载ButtonStyle是否存在于应用程序的资源字典中,且在窗口初始化时能够成功查找和应用。

    2. 检查构造函数调用:在Display()方法中创建MyMessageBox实例时,所有参数是否有效,尤其是Window owner。如果owner窗口已关闭或不存在,可能会导致异常。

    3. 事件处理程序异常:检查按钮点击事件和其他事件处理程序中的逻辑,特别是SaveFileDialog部分。例如,在尝试写入文件时可能出现未捕获的异常,这可能导致窗口关闭。

    4. UI线程阻塞:动画、对话框显示或其他长时间运行的任务可能阻塞UI线程,间接导致窗口无法正常显示。

    5. 内存泄漏或资源释放问题:检查是否有未正确释放的资源,比如COM对象或者其他非托管资源,它们可能在某个时刻引发异常。

    6. 自定义窗口样式和尺寸:根据你提供的代码片段,你为不同的消息框样式设置了不同的背景色和尺寸。请确认这些设置不会影响窗口的基本布局或渲染。

    为了更深入地定位问题,你可以通过添加调试语句或者使用Visual Studio的调试工具来逐步执行代码,观察哪个步骤出现问题。可以尝试在关键位置(如构造函数开始、结束以及每个事件处理程序内部)加入Debug.WriteLine()来输出日志信息,从而了解程序执行的流程。

    另外,也可以尝试在App.xaml.csAppDomain.CurrentDomain.UnhandledException事件中添加处理器,以便全局捕获未处理的异常,帮助确定问题所在。

    由于目前提供的信息尚不足以确切指出问题所在,若要进行进一步的故障排除,请提供更多关于崩溃时的具体错误信息、堆栈跟踪及上下文环境等详细情况。

    评论

报告相同问题?

问题事件

  • 修改了问题 2月9日
  • 创建了问题 2月9日

悬赏问题

  • ¥15 Hadoop的部署与安装的一些疑问
  • ¥15 短剧的sdk在哪里接入
  • ¥30 智能割草机自动化割草
  • ¥15 求:可不可以提供一些 在国内可以用,低代码不要太难 在电脑上可以下载的 制作app的软件
  • ¥60 找人回答kibana8.14.3二次集成开发,自定义插件ui导航栏如何设置
  • ¥15 fluke高精度万用表8845A型号测交流电压一直跳动,且去掉输入后显示不归零
  • ¥15 不同模型怎么用同一个shader
  • ¥15 安卓启动没有ais proxy与v4l2的log打印
  • ¥15 go怎么读取mdb文件里面的数据
  • ¥60 Matlab联合CRUISE仿真编译dll文件报错