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
.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With