Set default value in label if value is 0

RyanSappRyanSapp Ryan SappUSMember

I have been spending way too much time on something that I thought would be simple. If the label text value shows "0", I want to display "N/D" instead. I have tried the following with no success. Weight is a double field in my ViewModel.

        <Label
        Grid.Row="2"
        Grid.Column="1"
        Text="{Binding Weight}">
                <Label.Triggers>
                        <DataTrigger TargetType="Label" Binding="{Binding Weight, Converter={StaticResource IsZeroConverter}}" Value="True">
                            <Setter Property="Text" Value="N/D"/>
                        </DataTrigger>                      
                </Label.Triggers>       
       </Label>

The converter is below:

public class IsZeroConverter : IValueConverter
{
public IsZeroConverter()
{
}

    <a href="/search?Search=%23region&Mode=like">#region</a> IValueConverter implementation

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
  return (int)value == 0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {           
        throw new NotImplementedException();
    }

    <a href="/search?Search=%23endregion&Mode=like">#endregion</a>
}

}

Best Answer

Answers

  • ClintStLaurentClintStLaurent Clint StLaurent USUniversity ✭✭✭✭✭

    @RyanSapp

    I've never tried to do both the binding for content and the datatrigger like that.
    Usually you have to conditions on the data trigger.
    If trigger is true then value is {binding weight}
    if trigger is false then value is 'n\d]

  • RyanSappRyanSapp Ryan Sapp USMember

    I have also tried the following:

    <Label
        Grid.Row="2"
        Grid.Column="1"
                x:Name="test"
        Text="{Binding Weight}">
                  <Label.Triggers>
                    <DataTrigger TargetType="Label" Binding="{Binding Source={x:Reference test}, Path=Text.Value}" Value="0">
                      <Setter Property="Text" Value="N/D"/>
                    </DataTrigger>                      
                  </Label.Triggers>     
    </Label>
    
  • RyanSappRyanSapp Ryan Sapp USMember
    edited January 11

    Thanks @JimBennett

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
    return (int)value == 0 ? "N/D" : value.ToString();
    }
    

    XAML:

  • RyanSappRyanSapp Ryan Sapp USMember
        <Label
        Grid.Row="2"
        Grid.Column="1"
        Text="{Binding="{Binding Weight, Converter={StaticResource IsZeroConverter}}">
    
Sign In or Register to comment.