tags:

views:

561

answers:

3

I'm new to XAML, so presume I'm missing something simple. I want to replace the path part of the source path with a c# constant for easier path management, for example I have:

<Image Source="/Images/Themes/Buttons/MyPicture.png" />

and in another class I have my constant defined:

public static readonly string UriImagesButtons = "/Images/Big/PNG/";

I want to have something along the lines of:

<Image Source="{static:UriImagesButtons + MyPicture.png}" />

This means that I can change the path globally at a stroke if the need arises. What's the syntax to do this?

+2  A: 

Replacing the path means that you have to do a data binding... So why don't you save in your C# class the full file path and bind to it?

Maurizio Reginelli
I didn't want to go down that route as I have numerous images and it would mean that I needed a constant for each one, which negates any simplicity of management.
Philip
+1  A: 

You should take a look at the discussion on this thread: string manipulation in xaml attribute

Basically, you can create your own markup extension that takes 2 parameters and concatenates them. This particular example is also used for binding. I suspect you'd like to be able to bind to where you have the root path defined, or some other data perhaps.

Benny Jobigan
Ok, makes sense. Will that have a noticible performance hit if this is used extensively in an app?
Philip
Hmm, I don't know. I suppose it depends on what's "extensive".
Benny Jobigan
+3  A: 

The easiest way to do this is with a MultiBinding with a StringFormat:

<Path>
    <Path.Source>
        <MultiBinding StringFormat="{}{0}{1}">
            <Binding Mode="OneTime" Source="{x:Static lcl:ConstantOwner.UriImagesButtons}" />
            <Binding Mode="OneTime" Source="MyPicture.png" />
        </MultiBinding>
    </Path.Source>
</Path>

In the StringFormat parameter, you have to escape the first curly brace with a "{}" so the XAML parser doesn't think it is a markup extension.

Abe Heidebrecht
Neat solution. What surprises me about all of these though is that in old-school VB, you would just define a constant then the compiler would append that at compile time when it saw the string concatentation. Simple, code management is good and quick to implement.I'm really surprised that there does not appear to be a (simple) way of doing this in XAML?? Does everyone hard code all their paths in XAML or use one of the other methods in the (excellent) replies thus far? Seems like a major leap backwards in managability to me...?
Philip
+1. Nice. I like solutions that use existing things, instead of requiring that new ones be written.
Benny Jobigan
@Philip, in your code behind (could be C# of VB), you define the constant string in my solution. The MultiBinding is just the easiest built-in way to concatenate strings.
Abe Heidebrecht