Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding - Default value for empty string

Tags:

c#

binding

wpf

xaml

Is there a standard way to set a default or fallback value for a WPF binding if the bound string is empty?

<TextBlock Text="{Binding Name, FallbackValue='Unnamed'" /> 

The FallbackValue only seems to kick in when Name is null, but not when it is set to String.Empty.

like image 719
kroimon Avatar asked Mar 22 '13 10:03

kroimon


People also ask

What is the default binding mode in WPF?

Default Data-binding It just defines which is the default binding mode for the control's property. In WPF different controls has different default data-binding modes. For example, TextBlock's Text property has one-way as default binding mode but a TextBox's Text property has a two-way binding mode.

What is fallback value in WPF?

This is used when a binding cannot determine a value at all, based on the the data source and the path. Or in other words, FallbackValue is used when the property bound to the source is not at all available. In that case, the value supplied for FallbackValue will be considered at the target end.

What is TAG WPF?

In WPF, the FrameworkElement class includes a Tag property that allows storing some arbitrary data with an element. You'd normally use the Tag property to store some custom data on an element that inherits from FrameworkElement. In the example below, we store some custom data with two different Button objects. 1. 2.


1 Answers

DataTrigger is the way i do it like this:

<TextBox>   <TextBox.Style>         <Style TargetType="{x:Type TextBox}"  BasedOn="{StaticResource ReadOnlyTextBox}">             <Setter Property="Text" Value="{Binding Name}"/>             <Style.Triggers>                 <DataTrigger Binding="{Binding Path=Name.Length, FallbackValue=0, TargetNullValue=0}" Value="0">                     <Setter Property="Text" Value="{x:Static local:ApplicationLabels.NoValueMessage}"/>                 </DataTrigger>             </Style.Triggers>         </Style>     </TextBox.Style> </TextBox> 
like image 128
iltzortz Avatar answered Sep 28 '22 09:09

iltzortz