Set default value in label if value is 0

RyanSappRyanSapp USMember ✭✭

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()
{
}

    #region 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();
    }

    #endregion
}

}

Best Answer

Answers

  • ClintStLaurentClintStLaurent 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 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 USMember ✭✭
    edited January 2017

    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 USMember ✭✭
        <Label
        Grid.Row="2"
        Grid.Column="1"
        Text="{Binding="{Binding Weight, Converter={StaticResource IsZeroConverter}}">
    
Sign In or Register to comment.