Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Text of Xamarin Forms Label based on bool value

I am trying to have a label which can have two different text values. I will display one of the two based on a bool. I am aware that I can create a binding to my viewmodel which could have a property (e.g. LabelText) which can be changed. However I would need to set the text inside the viewmodel in that case and that feels a bit messy.

I am looking for some kind of converter (IValueConverter) that binds a bool on the text property and has two string Parameters. The converter then chooses the right string for the Text of the label. However, to my knowledge, it is not possible to have more than one parameter on a converter?

Any Ideas how to solve this in a clean fashion? Maybe somehow by subclassing Label, but how?

like image 932
user2074945 Avatar asked Nov 14 '18 15:11

user2074945


1 Answers

I would more prefer the Trigger on this case than the IValueConverter. Because with trigger you can have your Text inside the view itself. So If you want to change; you don't have to go find the logic outside of that label.

<Label Text="Hello World!">
            <Label.Triggers>
                    <DataTrigger TargetType="Label" Binding="{Binding IsActive}" Value="false">
                        <Setter Property="Text"  Value="Not Active" />
                    </DataTrigger>
                    <DataTrigger TargetType="Label" Binding="{Binding IsActive}" Value="true">
                        <Setter Property="Text"  Value="Active" />
                    </DataTrigger>
                </Label.Triggers>

</Label>

So here you are binding the Trigger with your Boolean property in your VM. If its True or False whenever it changes it would trig that trigger.

Just to let you know; You can even change other properties too! Lets say If you want to change the Color as well ? So this could be even more better solution for you than to use ValueConverter in this case.

Hope this helps. Let me know If you need more help.

like image 65
Nirmal Subedi Avatar answered Oct 19 '22 02:10

Nirmal Subedi