Search code examples
mauisyncfusion

How to bind property to ChipBackground of SfChipGroup?


I use a SfChipGroup and I bind as ItemSource a PageButtonList from my ViewModel.

private ObservableCollection<PageModel> _pageButtonList = new ObservableCollection<PageModel>();

public ObservableCollection<PageModel> PageButtonList
{
    get { return _pageButtonList; }
    set
    {
        _pageButtonList = value;
        OnPropertyChanged("PageButtonList");
    }
}

For the background color I will use a boolean property from the PageButtonList object IsCurrentPage. That for I use a BoolToColorConverter.

<toolkit:BoolToObjectConverter x:Key="BoolToColorConverter" 
                       TrueObject="{x:Static Colors.Red}"
                       FalseObject="{x:Static Colors.White}"/>

And use it like that:

<syncfusion:SfChipGroup ItemsSource="{Binding PageButtonList}"
                        DisplayMemberPath="Title"
                        ChipBackground="{Binding IsCurrentPage, Converter={StaticResource BoolToColorConverter}}"
                        ChipTextColor="Black"/>

The list object class PageModel looks like that:

public class PageModel
{
    public int Id { get; set; }

    public string Title => (Id + 1).ToString();

    public bool IsCurrentPage { get; set; }

    public PageModel(int id)
    {
        Id = id;
        IsCurrentPage = true;
    }
}

The problem is I get this error:

Binding: Property "IsCurrentPage" not found on "MyApp.ViewModels.MyPageViewModel".

The Property IsCurrentPage belongs to the object PageButtonList which is part of MyPageViewModel. The error message is right, but how can I tell the SfChipGroup the DataType is PageModel?


Solution

  • What you're trying to do is not possible like that. You will need to provide a DataTemplate to the SfChipGroup.ItemTemplate instead, but this also means that you will have to fully configure the SfChip yourself inside that template:

    <syncfusion:SfChipGroup ItemsSource="{Binding PageButtonList}">
        <syncfusion:SfChipGroup.ItemTemplate>
            <DataTemplate x:DataType="models:PageModel">
                <syncfusion:SfChip
                    Text="{Binding Title}"
                    TextColor="Black"
                    Background="{Binding IsCurrentPage, Converter={StaticResource BoolToColorConverter}}" />
            </DataTemplate>
        </syncfusion:SfChipGroup.ItemTemplate>
    </syncfusion:SfChipGroup>