Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed a System.String in XAML

Tags:

Is there a way to embed a string in XAML, give it and ID and refer to it later.

I have tried:

    <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> 

And get error:
Cannot add instance of type 'String' to a collection of type 'UIElementCollection'. Only items of type 'UIElement' are allowed.

Could I do this if I nested the String somewhere else in the XAML? or inside a non UI element? Then do I just give it a Name attribute?

like image 863
BuddyJoe Avatar asked Nov 30 '09 17:11

BuddyJoe


2 Answers

You should use Window.Resources

Here's an example for Page, in your case it will be Window.Resources tag:

<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> 
like image 167
Max Galkin Avatar answered Sep 28 '22 04:09

Max Galkin


In the Application tag you need to include the following:

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

without the above code, Visual Studio will complain about a missing assembly reference.

like image 27
FruityMo Avatar answered Sep 28 '22 05:09

FruityMo