簡體   English   中英

當我嘗試更改 TextBlock 文本時出錯

[英]Getting error when I try to change TextBlock text

我正在關注 Head First C# 3rd edition,在第一章中它要求我更改 TextBlock 的文本,但是當我嘗試時出現以下錯誤:

InvalidCastException:無法將“Windows.UI.Text.TextDecorations”類型的對象轉換為“System.Windows.TextDecorationCollection”類型。

在此處輸入圖片說明

這本書建議我將 Visual Studio Express 2012 用於 Windows 8,我正在遵循這些建議。

XAML 代碼:

<common:LayoutAwarePage
    x:Name="pageRoot"
    x:Class="Save_The_Humans.MainPage"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Save_The_Humans"
    xmlns:common="using:Save_The_Humans.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>

        <!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
        <x:String x:Key="AppName">Save The Humans</x:String>
    </Page.Resources>

    <!--
        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    -->
    <Grid Style="{StaticResource LayoutRootStyle}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="160"/>
            <ColumnDefinition/>
            <ColumnDefinition Width="160"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition/>
            <RowDefinition Height="160"/>
        </Grid.RowDefinitions>

        <!-- Back button and page title -->
        <Grid Grid.ColumnSpan="3">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button x:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResource BackButtonStyle}"/>
            <TextBlock x:Name="pageTitle" Grid.Column="1" Text="{StaticResource AppName}" Style="{StaticResource PageHeaderTextStyle}"/>
        </Grid>
        <Button x:Name="startButton" Content="Start!" HorizontalAlignment="Center" Grid.Row="2" VerticalAlignment="Center" 
                RenderTransformOrigin="0.562,0.526"/>
        <ProgressBar Grid.Column="1" HorizontalAlignment="Left" Height="10" Margin="475,37,0,0" Grid.Row="2" VerticalAlignment="Top" Width="100"/>
        <StackPanel Grid.Column="2" Margin="33,37,50,85" Orientation="Vertical" Grid.Row="2">
            <ContentControl Content="ContentControl" HorizontalAlignment="Left" VerticalAlignment="Top"/>
        </StackPanel>
        <Canvas Grid.Column="1" HorizontalAlignment="Left" Height="100" 
                Margin="475,175,0,0" Grid.Row="1" VerticalAlignment="Top" Width="100"/>

        <TextBlock Grid.Column="2" HorizontalAlignment="Left" Margin="24,2,0,0" Grid.Row="2" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Style="{StaticResource SubheaderTextStyle}"/>

        <VisualStateManager.VisualStateGroups>

            <!-- Visual states reflect the application's view state -->
            <VisualStateGroup x:Name="ApplicationViewStates">
                <VisualState x:Name="FullScreenLandscape"/>
                <VisualState x:Name="Filled"/>

                <!-- The entire page respects the narrower 100-pixel margin convention for portrait -->
                <VisualState x:Name="FullScreenPortrait">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PortraitBackButtonStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>

                <!-- The back button and title have different styles when snapped -->
                <VisualState x:Name="Snapped">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedBackButtonStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="pageTitle" Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedPageHeaderTextStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Grid>
</common:LayoutAwarePage>

源代碼

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace Save_The_Humans
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MainPage : Save_The_Humans.Common.LayoutAwarePage
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }
    }
}

錯誤文本:

InvalidCastException: Unable to cast object of type 'Windows.UI.Text.TextDecorations' to type 'System.Windows.TextDecorationCollection'.

堆棧跟蹤

 at Microsoft.Expression.DesignSurface.Tools.Text.TextBlockEditProxy.Instantiate()
   at Microsoft.Expression.DesignSurface.Tools.Text.TextEditProxy.AddToScene(Boolean visible)
   at Microsoft.Expression.DesignSurface.Tools.Text.TextToolBehavior.AddEditProxyToScene(TextEditProxy textEditProxy, Boolean visible)
   at Microsoft.Expression.DesignSurface.Tools.Text.TextToolBehavior.FindOrCreateEditProxy(SceneNode textElement, Boolean active)
   at Microsoft.Expression.DesignSurface.Tools.Text.TextToolBehavior.BeginTextEdit(SceneNode textElement)
   at Microsoft.Expression.DesignSurface.Tools.Text.TextToolBehavior.EditDifferentElement(SceneNode element, Boolean returnFocus)
   at Microsoft.Expression.DesignSurface.Tools.Text.TextToolBehavior.OnAttach()
   at Microsoft.Expression.DesignSurface.Tools.EventRouter.PushBehavior(ToolBehavior newActiveBehavior)
   at Microsoft.Expression.DesignSurface.View.SceneView.TryEnterTextEditMode(Boolean textElementOnly)
   at Microsoft.Expression.DesignSurface.SceneCommands.EditTextCommand.Execute()
   at Microsoft.Expression.Utility.Commands.CommandTarget.ExecuteCommand(String commandName, CommandInvocationSource invocationSource)
   at Microsoft.Expression.Utility.UserInterface.CommandBarButtonBase.<>c__DisplayClass1.<Execute>b__0()
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)

InnerException: None

為什么我有兩個減號?!

我錯誤地解決了問題,出現錯誤后我更改了 XAML 代碼中的文本值,問題解決了,但是當我單擊“編輯文本”時仍然出現錯誤。

圖像顯示問題

圖片顯示解決后

我遇到了同樣的問題,事實證明,這是因為我使用的是 Windows 10。

就我而言,您無法在較舊或較新的操作系統上構建 Windows 8 應用程序——歸根結底,這個 Visual Studio 是為 Windows 8 明確設計的,所以我想這是有道理的。

無論如何,解決問題的方法是使用本書的WPF版本。 你可以在作者的 Github 頁面上免費找到它 -> https://github.com/head-first-csharp/third-edition

所以我所做的是按照本書的規定安裝適用於 Windows 桌面的 Visual Studio 2013 Express,並遵循這條路線。

您首先構建完全相同的 Alien Invasion 應用程序,當我不得不重命名文本塊時,一切正常。 其他步驟也是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM