Ошибка приведения в UWP TreeView при сворачивании узлов - PullRequest
0 голосов
/ 27 мая 2020

Сегодня я столкнулся с действительно странной проблемой. У меня есть TreeView с DataTemplates для 2 c объектов, которые я хочу отобразить в дереве. После запуска программы все нормально. ДО ... ну ... иногда я получаю ошибку приведения, когда o1 не может быть приведен к типу 2, что правильно, потому что вы не можете его использовать, но я не вижу в этом необходимости, потому что у меня есть две таблицы данных для каждого типа . Для надежной реконструкции я использовал кнопку свернуть все, так как это происходит только на сворачивающихся узлах. Итак, может ли кто-нибудь объяснить, почему я столкнулся с этим конкретным исключением? Кроме того, есть ли способ отладки ошибок XAML?

Мой XAML

    x:Class="CookBook.Views.EditCategoryPage"
    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"
    xmlns:templateSelectors="using:CookBook.TemplateSelectors"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:models="using:CookBook.Core.Models.Entities"
    xmlns:enums="using:CookBook.Core.Models"
    xmlns:winui="using:Microsoft.UI.Xaml.Controls"
    xmlns:vs="using:CookBook.Views.VisualControls"
    xmlns:ro="using:CookBook.Views.VisualControls.ConditionallyReordableModels"
    xmlns:behaviors="using:CookBook.Behaviors"
    Style="{StaticResource PageStyle}"
    behaviors:NavigationViewHeaderBehavior.HeaderMode="Never"
    mc:Ignorable="d">

    <Page.Resources>
        <DataTemplate x:Key="CategoryTemplate" x:DataType="models:Category">
            <winui:TreeViewItem
                AutomationProperties.Name="{x:Bind Name}"
                ItemsSource="{x:Bind Childs}"
                IsExpanded="False"
                >
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="40" />
                        <ColumnDefinition Width="*" />
                        <!--<ColumnDefinition />
                        <ColumnDefinition />-->
                    </Grid.ColumnDefinitions>
                    <SymbolIcon Grid.Column="0" Symbol="Folder"/>
                    <TextBlock Grid.Column="1" Width="auto" Text="{x:Bind Name}" HorizontalAlignment="Left" />
                    <!--<Button Grid.Column="2">
                        <FontIcon Glyph="&#xE010;" FontSize="{StaticResource AutoSuggestBoxIconFontSize}"/>
                    </Button>
                    <Button Grid.Column="3">
                        <FontIcon Glyph="&#xE011;" FontSize="{StaticResource AutoSuggestBoxIconFontSize}"/>
                    </Button>-->
                </Grid>
            </winui:TreeViewItem>

        </DataTemplate>

        <DataTemplate x:Key="CategoryContentTemplate" x:DataType="models:Category">
            <StackPanel Margin="10,10" Orientation="Vertical">
                <StackPanel VerticalAlignment="Bottom" Orientation="Horizontal" Margin="{StaticResource XXSmallTopRightBottomMargin}">
                    <TextBox Width="250" x:Name="tbName" Text="{x:Bind Path=EditItem.Title, Mode=TwoWay}" Header="Kategorie-Bezeichnung" VerticalAlignment="Center" />
                    <Button x:Name="btnCopyTitleFromCB" Margin="{StaticResource MediumLeftMargin}" Click="btnCopyTitleFromCB_Click" VerticalAlignment="Bottom">
                        <SymbolIcon Symbol="Paste" />
                    </Button>
                </StackPanel>
                <Grid Margin="{StaticResource XXSmallTopRightBottomMargin}">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition MinWidth="100" MaxWidth="350" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <StackPanel Orientation="Vertical" Grid.Column="1" Grid.Row="1">
                        <TextBlock VerticalAlignment="Top" Margin="{StaticResource SmallTopMargin}" TextWrapping="WrapWholeWords">Vorschaubild (wird auf maximal 200 Pixel Kantenlänge reduziert)</TextBlock>
                        <StackPanel Orientation="Horizontal">
                            <Button x:Name="btnAddPhoto" Content="Bild ändern" Click="btnAddPhoto_Click" Margin="{StaticResource MediumLeftTopRightBottomMargin}" />
                            <Button x:Name="btnAddPhotoFromClipBoard" Click="btnAddPhotoFromClipBoard_Click" Margin="{StaticResource SmallTopBottomMargin}">
                                <SymbolIcon Symbol="Paste" />
                            </Button>
                        </StackPanel>
                    </StackPanel>
                    <Image Grid.RowSpan="2" Grid.Column="0" Grid.Row="0" Margin="3" Width="200" Height="200" Name="imageThumb" Source="{ x:Bind Path=EditItem.Image.Image, Mode=OneWay}" VerticalAlignment="Center" />

                </Grid>
                <Grid Grid.Row="3" Grid.Column="1">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="100" />
                        <ColumnDefinition Width="100" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="100" />
                    </Grid.ColumnDefinitions>
                    <Button Grid.Row="0" Grid.Column="0" x:Name="SaveBtn" Content="Speichern" Margin="{StaticResource XXSmallTopRightBottomMargin}" Click="SaveBtn_Click" />
                    <Button Grid.Row="0" Grid.Column="1" x:Name="CancelBtn" Content="Abbrechen" Margin="{StaticResource XXSmallTopRightBottomMargin}" Click="CancelBtn_Click"/>

                    <Button HorizontalAlignment="Right" Grid.Column="3" x:Name="DeleteBtn" Content="Löschen" Margin="{StaticResource XXSmallTopRightBottomMargin}" Click="DeleteBtn_Click" />
                </Grid>
            </StackPanel>

        </DataTemplate>

        <DataTemplate x:Key="ReceipeTemplate" x:DataType="models:Receipe">
            <!--<ro:ReordableTreeViewItem AutomationProperties.Name="{x:Bind Title}" >-->
            <winui:TreeViewItem>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
                    <SymbolIcon Symbol="Document" Margin="5,5,5,5"/>
                    <TextBlock Text="{x:Bind Title}" Margin="{StaticResource XXSmallTopRightBottomMargin}" />
                </StackPanel>
            </winui:TreeViewItem>
        </DataTemplate>

        <DataTemplate x:Key="ReceipeContentTemplate" x:DataType="models:Receipe">
            <Grid HorizontalAlignment="Stretch">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="300"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="50"/>
                </Grid.RowDefinitions>
                <StackPanel Grid.Row="0" Grid.Column="0" Orientation="Vertical" >
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="100" />
                        </Grid.ColumnDefinitions>
                        <TextBox Grid.Column="0" Header="Titel" Text="{x:Bind EditItem.Title, Mode=TwoWay}" Width="auto"/>
                        <Button Grid.Column="1" x:Name="btnCopyTitleFromCB" Margin="{StaticResource MediumLeftMargin}" Click="btnCopyTitleFromCB_Click" VerticalAlignment="Bottom">
                            <SymbolIcon Symbol="Paste" />
                        </Button>
                    </Grid>
                    <StackPanel Orientation="Vertical" Margin="{StaticResource MediumTopMargin}">
                        <CheckBox x:Name="cbMeat" Content="Fleisch" IsChecked="{x:Bind ((models:Receipe)EditItem).IsMeat, Mode=TwoWay}"/>
                        <CheckBox x:Name="cbVegetarisch" Content="Vegetarisch" IsChecked="{x:Bind ((models:Receipe)EditItem).IsVegetarian, Mode=TwoWay}"/>
                        <CheckBox x:Name="cbVegan" Content="Vegan" IsChecked="{x:Bind ((models:Receipe)EditItem).IsVegan, Mode=TwoWay}"/>
                    </StackPanel>
                    <Grid Margin="{StaticResource MediumTopBottomMargin}">
                        <StackPanel VerticalAlignment="Stretch">
                            <TextBlock Text="Zutaten" Style="{StaticResource SubTitles }"/>
                            <controls:DataGrid
                                AutoGenerateColumns="false"
                                GridLinesVisibility="Horizontal"
                                VerticalAlignment="Stretch"
                                IsDoubleTapEnabled="False"
                                Loaded="DataGrid_Loaded" CellEditEnded="DataGrid_CellEditEnded" SelectionChanged="DataGrid_SelectionChanged" 
                                SelectionMode="Single" BeginningEdit="DataGrid_BeginningEdit" KeyUp="DataGrid_KeyUp">
                                <controls:DataGrid.Columns>
                                    <controls:DataGridTextColumn x:Name="colAmount" Binding="{Binding Amount}" Header="Menge" />
                                    <controls:DataGridComboBoxColumn x:Name="colUnit" Binding="{Binding Unit}" ItemsSource="{x:Bind enums:Enums.GetValues()}" Header="Einheit" />
                                    <controls:DataGridTextColumn x:Name="colName" Binding="{Binding Name}" Header="Zutat" Width="*"/>
                                    <controls:DataGridTemplateColumn Header="">
                                        <controls:DataGridTemplateColumn.CellTemplate>
                                            <DataTemplate>
                                                <Button Click="DeleteIngredient" Background="Transparent">
                                                    <SymbolIcon Symbol="Delete" />
                                                </Button>
                                            </DataTemplate>
                                        </controls:DataGridTemplateColumn.CellTemplate>
                                    </controls:DataGridTemplateColumn>
                                </controls:DataGrid.Columns>
                            </controls:DataGrid>
                        </StackPanel>
                    </Grid>
                    <!--<Button x:Name="btnPasteIngredients" Click="btnPasteIngredients_Click" Margin="{StaticResource SmallTopBottomMargin}">
                        <SymbolIcon Symbol="Paste" />
                    </Button>-->
                </StackPanel>

                <StackPanel Grid.Row="0" Grid.Column="1"
                        VerticalAlignment="Stretch"
                        Orientation="Vertical"
                        Margin="{StaticResource MediumLeftMargin}">
                    <Image  Name="recImg" Source="{ x:Bind Path=EditItem.Image.Image, Mode=OneWay}" VerticalAlignment="Center" Margin="{StaticResource MediumTopBottomMargin}"/>
                    <StackPanel Orientation="Vertical" Grid.Column="1" Grid.Row="1">
                        <TextBlock VerticalAlignment="Top" Margin="{StaticResource SmallTopMargin}" TextWrapping="WrapWholeWords">Vorschaubild (wird auf maximal 200 Pixel Kantenlänge reduziert)</TextBlock>
                        <StackPanel Orientation="Horizontal">
                            <Button x:Name="btnAddPhoto" Content="Bild ändern" Click="btnAddPhoto_Click" Margin="{StaticResource MediumLeftTopRightBottomMargin}" />
                            <Button x:Name="btnAddPhotoFromClipBoard" Click="btnAddPhotoFromClipBoard_Click" Margin="{StaticResource SmallTopBottomMargin}">
                                <SymbolIcon Symbol="Paste" />
                            </Button>
                        </StackPanel>
                    </StackPanel>
                </StackPanel>

                <StackPanel Grid.Row="1" Grid.ColumnSpan="2" Margin="{StaticResource MediumTopBottomMargin}">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="50" />
                            <ColumnDefinition Width="50" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Style="{StaticResource SubTitles }" Text="Arbeitsschritte" />
                        <Button Grid.Column="1" x:Name="btnCopyTextFromCB" Margin="{StaticResource SmallTopBottomMargin}" Click="btnCopyTextFromCB" VerticalAlignment="Top" HorizontalAlignment="Right">
                            <SymbolIcon Symbol="Paste"/>
                        </Button>
                        <Button Grid.Column="2" x:Name="btnDeleteCRLF" Margin="{StaticResource SmallTopBottomMargin}" Click="btnDeleteCRLF_Click" VerticalAlignment="Top" HorizontalAlignment="Right">
                            <SymbolIcon Symbol="ShowResults"/>
                        </Button>
                    </Grid>

                    <vs:BindableRichEditBox Height="auto" x:Name="editor" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Text="{Binding Path=EditItem.Steps, Mode=TwoWay}" />
                </StackPanel>

                <Grid Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="100" />
                        <ColumnDefinition Width="100" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="100" />
                    </Grid.ColumnDefinitions>
                    <Button Grid.Row="0" Grid.Column="0" x:Name="SaveBtn" Content="Speichern" Margin="{StaticResource XXSmallTopRightBottomMargin}" Click="SaveBtn_Click" />
                    <Button Grid.Row="0" Grid.Column="1" x:Name="CancelBtn" Content="Abbrechen" Margin="{StaticResource XXSmallTopRightBottomMargin}" Click="CancelBtn_Click"/>

                    <Button HorizontalAlignment="Right" Grid.Column="3" x:Name="DeleteBtn" Content="Löschen" Margin="{StaticResource XXSmallTopRightBottomMargin}" Click="DeleteBtn_Click" />
                </Grid>

            </Grid>
        </DataTemplate>


        <templateSelectors:CategoryDataTemplateSelector x:Key="TreeViewTemplateSelector"
            CategoryTemplate="{StaticResource CategoryTemplate}"
            ReceipeTemplate="{StaticResource ReceipeTemplate}" />

        <templateSelectors:CategoryDataTemplateSelector x:Key="ContentTemplateSelector"
            CategoryTemplate="{StaticResource CategoryContentTemplate}"
            ReceipeTemplate="{StaticResource ReceipeContentTemplate}" />

    </Page.Resources>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition x:Name="treeViewColumn" MinWidth="150" MaxWidth="350" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup>
                <VisualState>
                    <VisualState.StateTriggers>
                        <!--641 is the default CompactModeThresholdWidth in NavigationView -->
                        <AdaptiveTrigger MinWindowWidth="641" />
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter Target="header.Margin" Value="0,0,0,0" />
                        <Setter Target="treeViewColumn.Width" Value="350" />
                        <Setter Target="treeViewColumn.MaxWidth" Value="500" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <Grid
            Background="{ThemeResource SystemChromeMediumLowColor}">
            <Grid.RowDefinitions>
                <RowDefinition Height="40" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <Grid
                Margin="80,0,0,0"
                x:Name="header">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <TextBlock
                    x:Uid="TreeViewTitle"
                    Margin="{StaticResource SmallLeftMargin}"
                    Style="{StaticResource ListTitleStyle}"
                    VerticalAlignment="Center" />
                <!--Fold all-->
                <Button
                    Grid.Column="1"
                    x:Uid="TreeView_CollapseAllButton"
                    Content="&#xF165;"
                    FontSize="14"
                    Padding="{StaticResource SmallLeftRightMargin}"
                    VerticalAlignment="Stretch"
                    VerticalContentAlignment="Center"
                    FontFamily="Segoe MDL2 Assets"
                    Background="Transparent"
                    Click="OnCollapseAll" />
                <!--Add-->
                <Button
                    Grid.Column="2"
                    x:Uid="Flyoutbutton"
                    Content="&#xE710;"
                    FontSize="14"
                    Padding="{StaticResource SmallLeftRightMargin}"
                    VerticalAlignment="Stretch"
                    VerticalContentAlignment="Center"
                    FontFamily="Segoe MDL2 Assets"
                    Background="Transparent">
                    <Button.Flyout>
                        <MenuFlyout>
                            <MenuFlyoutItem Text="Neue Kategorie" Click="AddCategory" ></MenuFlyoutItem>
                            <MenuFlyoutItem x:Name="btnCatIn" Text="{x:Bind CategoryInText,Mode=OneWay}" Click="AddCategory"/>
                            <MenuFlyoutSeparator/>
                            <MenuFlyoutItem x:Name="btnReceipeIn" Text="{x:Bind ReceipeInText,Mode=OneWay}" Click="AddReceipe"/>
                        </MenuFlyout>
                    </Button.Flyout>
                </Button>
            </Grid>

            <winui:TreeView
                BorderBrush="Beige"
                BorderThickness="1"
                x:Name="treeView"
                Grid.Row="1"
                SelectionMode="Single" 
                ItemsSource="{x:Bind CategoryItems,Mode=OneWay}"
                ItemInvoked="OnItemInvoked"
                ItemTemplateSelector="{StaticResource TreeViewTemplateSelector}"
                CanReorderItems="False"
                Width="auto"
                >
                <winui:TreeView.ItemContainerStyle>
                    <Style TargetType="winui:TreeViewItem">
                        <Setter Property="VerticalAlignment" Value="Stretch" />
                        <Setter Property="VerticalContentAlignment" Value="Stretch" />
                    </Style>
                </winui:TreeView.ItemContainerStyle>

            </winui:TreeView>
        </Grid>
        <ScrollViewer
            Grid.Column="1"
            Padding="{StaticResource DetailPageMargin}">
            <ContentControl
                Content="{x:Bind SelectedItem, Mode=OneWay}"
                ContentTemplateSelector="{StaticResource ContentTemplateSelector}"
                HorizontalAlignment="Stretch"
                VerticalAlignment="Stretch"
                VerticalContentAlignment="Stretch"
                HorizontalContentAlignment="Stretch"/>
        </ScrollViewer>

        <controls:GridSplitter
            Grid.Column="1"
            GripperCursor="Default"
            HorizontalAlignment="Left"
            ResizeDirection="Auto"
            ResizeBehavior="BasedOnAlignment"
            CursorBehavior="ChangeOnSplitterHover"
            Width="16" />
    </Grid>
</Page>

и моя функция свертывания всех:

        {
            try
            {
                if (treeView.RootNodes.Count == 0) return;
                treeView.SelectedNode = treeView.RootNodes[0];
                CollapseNodes(treeView.RootNodes);
            }
            catch
            {
                Debug.WriteLine("EXCEPTION");
            }
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...