当我尝试添加日志时,Visual Studio 抛出 DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION

问题描述 投票:0回答:1

当我尝试使用以下代码(用于记录剧院旅行的应用程序)添加日志或搜索日志时,我会被发送到 App.g.i.cs 自动生成的代码。我使用了断点并逐步执行了代码,它似乎完成了整个子例程,然后当它到达末尾时它抛出了这个,也许是 UI 的问题?

#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
            UnhandledException += (sender, e) =>
            {
                if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
            };
#endif

这是我的主页xaml代码

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyTheatreLog.MainPage"
             xmlns:viewmodel="clr-namespace:MyTheatreLog.ViewModel"
             x:DataType="viewmodel:MainViewModel"
             Title="Theatre Log">

    <Grid RowDefinitions="50, Auto, Auto, *, Auto"
          ColumnDefinitions=".8*,.05*,.15*"
          Padding="10"
          RowSpacing="10"
          ColumnSpacing="10">


        <Entry Placeholder="New Log"
               Grid.ColumnSpan="3"
               Text="{Binding Show}"
               Grid.Row="1"/>
        <DatePicker Grid.Row="2"
                    Grid.Column="0"
                    Date="{Binding Date}"/>

        <Button Text="+"
                FontSize="30"
                WidthRequest="20"
                HeightRequest="20"
                Command="{Binding AddCommand}"
                Grid.Row="2"
                Grid.Column="3"
                HorizontalOptions="End"/>

        <CollectionView Grid.Row="3" Grid.ColumnSpan="3"
                ItemsSource="{Binding Shows}"
                SelectionMode="None"
                        >

            <CollectionView.ItemTemplate>

                <DataTemplate x:DataType="viewmodel:ShowItem">
                    <SwipeView>
                        <Grid Padding="0,5">
                            <Frame CornerRadius="8"
                           HasShadow="True">
                                <Frame.GestureRecognizers>
                                    <TapGestureRecognizer NumberOfTapsRequired="2"
                                                          Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}, Path=DetailsCommand}"
                                                          CommandParameter="{Binding .}"/>
                                </Frame.GestureRecognizers>
                                <Grid ColumnDefinitions="*, 90">
                                    <Label Text="{Binding Title}"
                                           Grid.Column="0"
                                           FontSize="14"/>
                                   <Label Text="{Binding DateString}"
                                          Grid.Column="1"/>
                                </Grid>

                            </Frame>
                        </Grid>
                    </SwipeView>
                </DataTemplate>

                </CollectionView.ItemTemplate>
        </CollectionView>

        
        <Entry Placeholder="Search Logs" 
               Grid.Row="4"
               Text="{Binding Searchentry}"/>
        <Button Grid.Row="4"
                Grid.Column="1"
                Grid.ColumnSpan="2"
                Text="Search"
                Command="{Binding SearchCommand}"/>

    </Grid>

</ContentPage>

和我的 ViewModel 代码

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;

namespace MyTheatreLog.ViewModel
{

    public class ShowItem
    {
        public string Title { get; set; }
        public string DateString { get; set; }
    }
    public partial class MainViewModel : ObservableObject
    {
        private LocalDatabase localDatabase;

        string appDataDirectory = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyTheatreLog");
        public MainViewModel()
        {

            if (!Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyTheatreLog")))
            {
                Directory.CreateDirectory(Path.Combine(appDataDirectory, "MyTheatreLog"));
            }
            
            Shows = new ObservableCollection<ShowItem>();
            localDatabase = new LocalDatabase();
            LoadLogs();


        }


        public void LoadLogs()
        {
            try
            {
                
                string[] logfiles = Directory.GetFiles(appDataDirectory, "*.txt");
                Shows.Clear();
                foreach (string file in logfiles)
                {
                    using(StreamReader savefile = new StreamReader(file))
                    {
                        Title = savefile.ReadLine();
                        Datestring = savefile.ReadLine();
                        savefile.Close();
                    }

                    if (!string.IsNullOrEmpty(Title) && !string.IsNullOrEmpty(Datestring))
                    {
                        var showItem = new ShowItem { Title = Title, DateString = Datestring };
                        Shows.Add(showItem);
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("Error loading logs " + ex.Message);
            }
        }

        [ObservableProperty]
        ObservableCollection<ShowItem> shows;

        [ObservableProperty]
        string show;

        bool searching = false;

        [ObservableProperty]
        string title;

        [ObservableProperty]
        DateTime date = DateTime.Today;

        [ObservableProperty]
        string searchentry;

        [ObservableProperty]
        string filename;

        [ObservableProperty]
        String datestring;


        [RelayCommand]
        void Add()
        {
            // checks if entry is empty
            if (string.IsNullOrWhiteSpace(Show))
                return;
            Datestring = Date.ToString("dd/MM/yyyy");
            // adds show
            Show = Show.Trim();
            string filetitle = Show.Replace(" ", "") + Datestring.Replace("/", "");
            Filename = filetitle + ".txt";


            using (StreamWriter savefile = new StreamWriter(System.IO.Path.Combine(appDataDirectory, Filename), true))
            {
                //saves to file
                savefile.WriteLine(Show);
                savefile.WriteLine(Datestring);
                savefile.Close();
            }
            LoadLogs();
            Show = string.Empty;

        }

        [RelayCommand]

        void Search()
        {
            try
            {
                var Showsholder = new ObservableCollection<ShowItem>();
                Showsholder.Clear();
                if (searching == false)
                {
                    // checks if entry is empty
                    if (string.IsNullOrWhiteSpace(Searchentry))
                        return;

                    // fills Shows placeholder

                    foreach (var log in Shows)
                    {
                        Showsholder.Add(log);
                    }
                    Shows.Clear();
                    Searchentry = Searchentry.Trim();
                    Searchentry = Searchentry.ToLower();
                    foreach (var log in Showsholder)
                    {
                        string logtitle = log.Title;
                        string logsearched = logtitle.ToLower();

                        // Adds logs that match search
                        if (logsearched.Contains(Searchentry))
                        {
                            Shows.Add(log);
                        }
                    }

                    searching = true;
                }
                else
                {
                    Shows.Clear();
                    LoadLogs();
                    searching = false;
                }
                Searchentry = string.Empty;
            }
            catch
            {
                Console.WriteLine("Error Searching");
            }

        }

        [RelayCommand]
        async Task Details(ShowItem s)
        {
            //navigates to Details Page
            string filetitle = s.Title.Replace(" ", "");
            string filedate = s.DateString.Replace("/", "");
            Filename = filetitle + filedate + ".txt";
            await Shell.Current.GoToAsync($"{"Details"}?Filename_={Filename}");
        }


    }
}

我对毛伊岛很陌生,我一直在尽力阅读并解决它,但没有运气

包含项目信息的新文件确实会在正确的位置以正确的名称创建,并在我下次运行代码时显示。

c# xaml maui
1个回答
0
投票

我遇到了同样的问题,我的问题是使用 x:Bind。

我需要使用绑定并更改模式:

<TextBlock Name="avgTimeDisplay" Text="{Binding AvgTime, Mode=TwoWay}" Visibility="{Binding LabelVisible, Mode=TwoWay}" ></TextBlock>

这与设置我的 ViewModel 一起:

public string AvgTime
{
    get => avgTime;
    set => SetProperty(ref avgTime, value);
}
© www.soinside.com 2019 - 2024. All rights reserved.