在XAML中嵌入System.String

yduiuuwa  于 2022-12-07  发布在  其他
关注(0)|答案(5)|浏览(195)

有没有办法在XAML中嵌入一个字符串,给予它一个ID,以后再引用它。
我试过:

<Window x:Class="WpfApp1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        Title="Window1" Height="300" Width="500">
        <Grid>
            <System:String>Test</System:String>
        </Grid>
    </Window>

并得到错误:
无法将"String“类型的示例添加到”UIElementCollection“类型的集合中。只允许”UIElement“类型的项。
如果我将String嵌套在XAML中的其他地方,或者嵌套在非UI元素中,我可以这样做吗?那么我只给予它一个Name属性吗?

mctunoxg

mctunoxg1#

您应该使用Window.Resources
下面是Page的一个示例,在您的示例中,它将是Window.Resources标记:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:System="clr-namespace:System;assembly=mscorlib">
  <Page.Resources>
    <System:String x:Key="MyString">Hello</System:String>
  </Page.Resources>
  <Grid>  
    <TextBlock Text="{StaticResource MyString}"></TextBlock>
  </Grid>
</Page>
thigvfpy

thigvfpy2#

在Application标记中,您需要包括以下内容:

xmlns:system="clr-namespace:System;assembly=mscorlib">

如果没有上面的代码,VisualStudio将报告缺少程序集引用。

1tu0hz3e

1tu0hz3e3#

我不知道为什么,但在我的.Net Core 3 WPF应用程序中,我应该使用以下xmlns定义而不是“mscorlib”:

xmlns:system="clr-namespace:System;assembly=System.Runtime"

那么我可以定义:

<system:Double x:Key="FontSizeLarge">24</system:Double>

<system:String x:Key="StringTest">Test</system:String>
njthzxwz

njthzxwz4#

引用字符串将不允许您以后更改它,因为字符串是不可变的,所以正如Yacoder建议的那样,只需将它放在<Window.Resources>部分中即可。

<Window.Resources>
        <System:String x:Key="TestString">Test</System:String>
</Window.Resources>

如果需要能够更改网格中显示的字符串的值,则需要使用TextBlock或其他可以设置其Content属性的控件。

iqxoj9l9

iqxoj9l95#

如果您像我一样,在XAML文件中的某个地方输入了不需要的额外字符,您可能会遇到此错误。幸运的是,我有GIT监视,所以"与未修改的比较"很快就显示了我在某个地方错误输入的字符。希望这可以为您节省一些头发。:)

相关问题