0
votes

What i am trying to do is, I created a ViewCell and bound it to ListView. In ViewCell, I have title label which I want to change as per data coming from the database. What would be the best practice to this?

Here my chunk of code

Model-

public class helplineservices
    {
        public string title { get; set; }
        public bool isenable { get; set; }
    }

ViewCell -

public class HelpLineCell : ViewCell
    {
        #region binding view cell logic
        public HelpLineCell()
        {
            BlackLabel title = new BlackLabel
            {
                FontFamily = Device.OnPlatform(
                            "Roboto-Black",
                            null,
                            null),
                FontSize = Device.OnPlatform(
                            (ScreenSize.getscreenHeight() / 47),
                            (ScreenSize.getscreenHeight() / 47),
                            14
                        ),
                HorizontalTextAlignment = TextAlignment.Center,
                TextColor = Color.FromHex("#FFFFFF"),
                WidthRequest = ScreenSize.getscreenWidth()
            };
            title.SetBinding(Label.TextProperty, "title");

            this.View = title;
        }
        #endregion
}

ListView -

var HelpList = new ListView
            {
                IsPullToRefreshEnabled = true,
                HasUnevenRows = true,
                BackgroundColor = Color.Transparent,
                RefreshCommand = RefreshCommand,
                //row_list is a list that comes from database
                ItemsSource = row_list,
                ItemTemplate = new DataTemplate(typeof(HelpLineCell)),
                SeparatorVisibility = SeparatorVisibility.None
            };

I want to change title color by checking a bool value of isenable which comes from database. Please help me.

1

1 Answers

0
votes

You have to Bind the TextColor like you have done for your Text property, then convert with a IValueConverter the Boolean value to a Color

Something like:

title.SetBinding(Label.TextColorProperty, new Binding("isenable", BindingMode.Default, new BooleanToColorConverter()));

Your IValueConverter should be something like

public class BooleanToColorConverter : IValueConverter {

    #region IValueConverter implementation

    public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value is bool)  {

            if(((bool) value) == true)
                return Color.Red;
            else
                return Color.Black;
        }
        return Color.Black;
    }

    public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException ();
    }

    #endregion
}

PS: NOT TESTED...

A useful article