Bud*_*Joe 16 .net silverlight wpf xaml
有没有办法在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>
Run Code Online (Sandbox Code Playgroud)
并获得错误:
无法将"String"类型的实例添加到"UIElementCollection"类型的集合中.仅允许"UIElement"类型的项目.
如果我将字符串嵌套在XAML中的其他位置,我可以这样做吗?或者在非UI元素中?然后我只给它一个Name属性?
Max*_*kin 31
你应该用 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>
Run Code Online (Sandbox Code Playgroud)
小智 5
在“应用程序”标签中,您需要包括以下内容:
xmlns:system="clr-namespace:System;assembly=mscorlib">
Run Code Online (Sandbox Code Playgroud)
如果没有上述代码,Visual Studio将抱怨缺少程序集引用。
我不知道为什么,但在我的 .Net Core 3 WPF 应用程序中,我应该使用这个 xmlns 定义而不是“mscorlib”:
xmlns:system="clr-namespace:System;assembly=System.Runtime"
Run Code Online (Sandbox Code Playgroud)
那么我可以定义:
<system:Double x:Key="FontSizeLarge">24</system:Double>
Run Code Online (Sandbox Code Playgroud)
或者
<system:String x:Key="StringTest">Test</system:String>
Run Code Online (Sandbox Code Playgroud)