Forum Xamarin Xamarin.Forms

Conditional Styling based on Data Binding values

Hi All,

I have an implementation of a ViewCell class, which I am using in a ListView. I'm happily able to bind data to the ViewCell, and display it in each list row.

However, I'd like to be able to vary the style of parts of my ViewCell according to the data that the cell is bound to.

As an example, if I had a model:

class Widget{
    public String foo {get; set;}
    public String bar {get; set;}
}

I might want to have a label with text set to the contents of "foo", who's colour varies according to the first letter of "bar".

Can anyone point me in the right direction? The only potential solution I've come across is to add a property to my Widget model - but this doesn't feel right. I shouldn't be adding style-related code to my data model! Could I implement an IValueConverter to achieve this? I've not been able to find any relevant examples in the docs (but perhaps I'm looking in the wrong place...).

Thanks!

Posts

  • ylemsoulylemsoul RUMember ✭✭✭

    You can use Data Trigger to achieve what you want. And/or combine it with the Style if you have applied some on the target label.

  • Luis_dmLuis_dm USMember ✭✭✭

    what is converter?

  • pikMRpikMR Member

    @JosephRedfern said:
    Hmmm. Having looked at the docs, I don't think that Data Triggers was what I was after.

    I ended up implementing IValueConverter:

    private class BarConverter : IValueConverter{
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture){
            var stringValue = (String)value;
            
            switch(stringValue[0]){
                case 'A':
                    return Color.White;
                case 'B':
                    return Color.Blue;
                default:
                    return Color.Orange;
             }
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){
            throw new NotImplementedException("Not implemented.");
        }
    }
    

    I then set the binding like this:

    fooLabel.SetBinding(Label.TextColorProperty, new Binding("bar", converter:new BarConverter()));
    

    The colour property of fooLabel now depends on the first character of the bar.

    Thanks this solve my problem!

Sign In or Register to comment.