Reputation: 3
I have a StackLayout that binds to a list and I would like to put each item's Text
property in a label, with different colors based on the IsSpecial
property in the following manner:
<StackLayout BindableLayout.ItemsSource="{Binding Lines}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Text}" TextColor= "Red if IsSpecial otherwise White"/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
I tried using triggers but I couldn't figure out how to reference the target type properly.
Upvotes: 0
Views: 220
Reputation: 8914
Since you're not showing the model class you're binding to, I'll make an educated guess:
public class Line
{
public string Text { get; set; }
public bool IsSpecial { get; set; }
}
or something like (if the values keep changing):
public partial class Line : ObservableObject
{
[ObservableProperty]
private string _text;
[ObservableProperty]
private bool _isSpecial;
}
Then you can use a DataTrigger like this:
<StackLayout BindableLayout.ItemsSource="{Binding Lines}">
<BindableLayout.ItemTemplate>
<DataTemplate x:DataType="model:Line">
<Label
Text="{Binding Text}"
TextColor="White">
<Label.Triggers>
<DataTrigger
TargetType="Label"
Binding="{Binding IsSpecial}"
Value="True">
<Setter
Property="TextColor"
Value="Red" />
</DataTrigger>
</Label.Triggers>
</Label>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
Note that I've also added the x:DataType
attribute to enable compiled bindings. That way, the binding expressions get evaluated during compile-time.
Upvotes: 2