Sabuncu
Sabuncu

Reputation: 5264

How to define and use a simple resource in XAML?

I am NEW to WPF. I have the following XAML code:

</Window>
        ...
    <Canvas>
        <TextBlock Canvas.Left="300" Canvas.Top="300">WORD1</TextBlock>
        <TextBlock Canvas.Left="350" Canvas.Top="300">WORD2</TextBlock>
        <TextBlock Canvas.Left="400" Canvas.Top="300">WORD3</TextBlock>
    </Canvas>
</Window>

I would like to define "300" as a resource (say "myTop") and replace all Canvas.Top="300" with Canvas.Top="myTop".

How can I do this in WPF/XAML? I looked into StaticResources and DataTemplates, but could not figure out a simple way. Thanks.

Upvotes: 0

Views: 1914

Answers (3)

TheEye
TheEye

Reputation: 9346

In Windows Phone 8.1, the type has to be a basic type of the XAML language, and can be accessed like this:

...
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
...

<Page.Resources>
    <x:Double x:Key="theTop">300</System:Double>
</Page.Resources>

See here: https://msdn.microsoft.com/en-us/library/hh771178.aspx

Upvotes: 1

JleruOHeP
JleruOHeP

Reputation: 10376

First of all you have to add xmlns to the window

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

And then define resource like this

<Window.Resources>
    <System:Double x:Key="theTop">300</System:Double>
</Window.Resources>

And then you can use it:

<Canvas>
  <TextBlock Canvas.Left="300" Canvas.Top="{StaticResource theTop}">WORD1</TextBlock>
</Canvas>

Upvotes: 3

Matt Hamilton
Matt Hamilton

Reputation: 204129

This one's a little trickier than you'd first think, because you essentially want to define a "constant" of type System.Double to reference later on.

To get to that type you'll need to use the System namespace from mscorlib.dll in your XAML, so add this line to the top of your file under the other namespace declarations:

xmlns:s="clr-namespace:System;assembly=mscorlib"

Now we can use that XML namespace to define our resource:

<Canvas>
    <Canvas.Resources>
        <s:Double x:Key="foo">300</s:Double>
    </Canvas.Resources>

... and refer to it from the TextBlocks:

    <TextBlock Canvas.Left="300" Canvas.Top="{StaticResource foo}">WORD1</TextBlock>
    <TextBlock Canvas.Left="350" Canvas.Top="{StaticResource foo}">WORD2</TextBlock>
    <TextBlock Canvas.Left="400" Canvas.Top="{StaticResource foo}">WORD3</TextBlock>
</Canvas>

Upvotes: 2

Related Questions