Tevis
Tevis

Reputation: 739

How to use variable text in a Binding StringFormat?

So I would like to have a variable StringFormat in a binding, but I'm not sure how to do that. I don't mind if it's XAML or code behind. Here's what I currently have:

<TextBlock x:Name="TextBlockSpellSkill" Text="{Binding CurrentValue, StringFormat=Spell: {0}}" />

However, I would like to be able to change the prefix "Spell:" to, for example "Skill:" based on a variable in my model. The easiest way would be if I could do it in code behind something like this:

if (true)
{
    TextBlockSpellSkill.StringFormat = "Spell: {0}";
}
else
{
    TextBlockSpellSkill.StringFormat = "Skill: {0}";
}

but I couldn't find any way to just set the string format from code-behind. If there's a good way to do it in XAML I'm cool with that too!

Thanks

Upvotes: 2

Views: 3646

Answers (2)

Ryan Emerle
Ryan Emerle

Reputation: 15811

You could do this in a number of ways. One way would be to use a Style Trigger.

<TextBlock x:Name="TextBlockSpellSkill" >
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Text" Value="{Binding CurrentValue, StringFormat=Spell: {0}}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding SomeFlag}" Value="True">
                    <Setter Property="Text" Value="{Binding CurrentValue, StringFormat=Skill: {0}}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

Another option would be to use an ValueConverter in your binding.

Upvotes: 2

123 456 789 0
123 456 789 0

Reputation: 10865

The StringFormat that you are using is for Binding. What you want to do is something like this

var textBlock = new TextBlock();
var binding = new Binding("CurrentValue");
binding.StringFormat = "Spell : {0}";
textBlock.SetBinding(TextBlock.TextProperty, binding);

Upvotes: 2

Related Questions