Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding with StringFormat

Could anyone explain to me why this does not render "VALUE IS DEFAULT"?

<TextBlock Text="{Binding Fail, StringFormat=VALUE IS {0}, FallbackValue=DEFAULT}" />

There is something tricky about this syntax I am missing. Thank you in advance.

like image 466
Jerry Nixon Avatar asked May 03 '11 16:05

Jerry Nixon


People also ask

How to use string format in WPF?

To do so, you provide the text to the StringFormat value and include a placeholder. The placeholder must include a reference number, which for a basic binding is always zero, surrounded by brace characters. For example, "{0}".

What is TextBlock WPF?

The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.

What is WPF MultiBinding?

MultiBinding takes multiple values and combines them into another value. There are two ways to do MultiBinding , either using StringFormat or by a converter. The StringFormat. is simple compared to a converter, so we will start with that first.


2 Answers

Binding in WPF does not consider StringFormat while falling back to FallbackValue in case it fails.

You can use what leon suggested or go with PriorityBinding.

--EDIT--

This should work:

<TextBlock DataContext="{Binding Fail, FallbackValue=DEFAULT}" Text="{Binding StringFormat=VALUE IS {0}}" />
like image 199
decyclone Avatar answered Nov 15 '22 07:11

decyclone


I think it could also work using the runs inside the TextBlock :

     <TextBlock>
             <Run Text="Value is : "/>
             <Run Text="{Binding Fail,FallbackValue=Default}"/>
     </TextBlock>

?

like image 41
Gerrrard Avatar answered Nov 15 '22 08:11

Gerrrard