2

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

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! Still new to the whole binding paradigm and XAML syntax for it makes my head hurt :) I'll accept when it opens up
@Tevis It's gonna be hard in the beginning but you'll see the awesomeness of bindings. Just keep doing it :)
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.