首页 > 解决方案 > 为什么 Xamarin Forms 应用程序的资源中的字符串会给出缺少默认构造函数错误?

问题描述

我正在尝试在 Application.Resources 部分中声明一个字符串。我在网上看到过这样的例子,但只有当系统程序集引用 mscorlib 时。

因此,如果我创建一个 WPF .Net Framework 应用程序,然后在 App.xaml 文件中有以下内容,这将成功编译:

<Application x:Class="WpfAppNETFrameworkTestString.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfAppNETFrameworkTestString"
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <sys:String x:Key="myString">my string</sys:String>
    </Application.Resources>
</Application>

但是,如果我创建一个 Xamarin Forms 移动应用程序并且在 App.xaml 文件中有以下内容:

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:sys="clr-namespace:System;assembly=netstandard"
             mc:Ignorable="d"
             x:Class="XamarinFormsTestString.App">
    <Application.Resources>
        <sys:String x:Key="myString">my string</sys:String>
    </Application.Resources>
</Application>

这会导致“缺少'System.String'的默认构造函数”的编译错误

有没有办法在资源部分中有一个字符串而不会出现这个错误?

标签: c#xamarin.forms

解决方案


如果你想把字符串Application.Resources放到Xamarin.Forms. 您可以添加String如下代码格式的选项卡。

<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="App24.App">
    <Application.Resources>
        <x:String x:Key="mystr">ssgsdgsdg</x:String>
    </Application.Resources>
</Application>

然后在其他布局中使用StaticResource

 <StackLayout>
        <!-- Place new controls here -->
        <Label Text="{StaticResource mystr}" 
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
    </StackLayout>

这是运行截图。

在此处输入图像描述


推荐阅读