Dot-Net

在 XAML 中嵌入 System.String

  • November 30, 2009

有沒有辦法在 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”類型的項目。

如果我將字元串嵌套在 XAML 中的其他位置,我可以這樣做嗎?還是在非 UI 元素內?那麼我只是給它一個 Name 屬性嗎?

你應該使用Window.Resources

這是頁面的範例,在您的情況下它將是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>

引用自:https://stackoverflow.com/questions/1821238