Home > Software engineering >  How to display a text according to the binding value in MAUI
How to display a text according to the binding value in MAUI

Time:01-11

I have a Label inside Collection View. It has a Binding value called IsCd and it only returns 0 or 1.I need to display yes if it returns 1 and if not no

<CollectionView ItemsSource="{Binding LHItems}">

            <CollectionView.ItemTemplate>
                <DataTemplate x:DataType="models:NewAppliedLeave">
                    
                            
                        <VerticalStackLayout>
                            
                                <Label Text="{Binding IsCd}" Grid.Row="0" Grid.Column="4"/>
                                
                        </VerticalStackLayout>
                    

                </DataTemplate>
            </CollectionView.ItemTemplate>
   </CollectionView>

I'm expecting display yes or no response instead of 1 or 0 .

CodePudding user response:

Did you check the official document about the Binding value converters? You can create an IntToString Converter, such as:

public class IntToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if ( (int)value == 0 ){
           return "no";
         }
        return "yes";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {     
    }
}

And then you can use it in the xaml as the example code in the official document does.

CodePudding user response:

You may either go with converters or use trigger mechanism:

<Label Grid.Row="0" Grid.Column="4">
    <Label.Style>
        <Style TargetType="Label">
            <Setter Property="Text" Value="no"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsCd}" Value="1">
                    <Setter Property="Text" Value="yes"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Label.Style>
</Label>
  • Related