Embed a System.String in XAML

Viewed 41260

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?

5 Answers

I don't know why, but in my .Net Core 3 WPF app I should use this xmlns definition instead of "mscorlib":

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

then I can define:

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

or

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

And if you're like me and have typed an unwanted extra character somewhere in the XAML file, you can get this error. Fortunately I had GIT watching over my shoulder, so "Compare with Unmodified" quickly revealed that character that I had mistakenly typed at a place. Hope this can save some hair for you. :)

Related