-_._- 2024-02-08 22:40 采纳率: 25%
浏览 7
已结题

C# 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条回答 默认 最新

  • 叫兽-郭老师 Java领域新星创作者 2024-02-08 22:42
    关注

    参考通义千问和郭老师的小迷弟雅思莫了-编写提供,主要是为了帮助您快速解决问题,如下回答,您可以参考下,如有问题,评论区留言。

    从你提供的代码来看,没有明显的错误会导致程序闪退。但是,为了更好地分析问题所在,请尝试以下步骤:

    1. MyMessageBox 构造函数中添加 try-catch 块来捕获可能的异常,并在 catch 部分输出异常信息,这样有助于确定闪退的具体原因:
    public MyMessageBox(string title, string content, Window owner, bool co, MyMessageBoxStyles style)
    {
        try
        {
            InitializeComponent();
            // ... 其他初始化代码
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error in MyMessageBox constructor: {ex.Message}");
            throw; // 如果你想让异常继续抛出以调试
        }
    }
    
    1. 检查你的资源文件(如样式资源 "ButtonStyle"),确保它在应用程序启动时正确加载。

    2. 确保 Display() 方法被正确调用,并且传递给它的 Window owner 参数在调用时不是 null。如果窗口已经关闭,而你尝试将其作为所有者窗口传递,则可能会导致问题。

    3. 使用 Visual Studio 的调试功能,逐步执行代码或者设置断点在可能出现问题的地方(例如构造函数或 Display() 方法内部),查看运行时变量的值和控制流,找出可能引起闪退的原因。

    4. 检查 XAML 文件中是否存在引用了不存在的资源或其他可能导致编译失败的问题。

    5. 如果以上都无法找到问题,可能需要检查是否有未显示的外部依赖或者非 UI 线程访问 UI 控件等问题。

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 2月9日
  • 修改了问题 2月9日
  • 修改了问题 2月9日
  • 创建了问题 2月8日

悬赏问题

  • ¥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文件报错