Home > Software design >  How pass ItemsSource to converter from one of control inside DataTemplate
How pass ItemsSource to converter from one of control inside DataTemplate

Time:12-20

I want to hide bullet point's circle control if collection has only one item in it. If collection count more than one then enable it.

This is my code

<StackLayout BindableLayout.ItemsSource="{Binding Description}">
<BindableLayout.ItemTemplate>
    <DataTemplate>
        <StackLayout>
            <cc:CustCircle
                IsVisible="{Binding .,Converter={StaticResource CollectionToCountConverter}}"
                CornerRadius="5">
            </cc:CustCircle>
            <Label
                   Text="{Binding .,Mode=TwoWay}">
            </Label>
        </StackLayout>
    </DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>

When I pass collection Description, converter is not getting called at all, when I pass Binding . converter value showing null.

How can I check collection count and enable disable cc:CustCircle ?

CodePudding user response:

We will have to provide name to our content page to access the parent binding properties inside data template.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MainPage"
             x:Name="mainpage">
<StackLayout x:Name="stackList" BindableLayout.ItemsSource="{Binding Description}">
<BindableLayout.ItemTemplate>
    <DataTemplate>
        <StackLayout>
            <cc:CustCircle
                IsVisible="{Binding Source={x:Reference mainpage},Path=BindingContext.Description.Count,Converter={StaticResource CollectionToCountConverter}}"
                CornerRadius="5">
            </cc:CustCircle>
            <Label
                   Text="{Binding .,Mode=TwoWay}">
            </Label>
        </StackLayout>
    </DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</ContentPage>

And in your CollectionToCountConverter just check

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if((int)value > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

Edit : If Page name is not working as expected use StackLayout name

 IsVisible="{Binding Source={x:Reference stackList},Path=BindingContext.Description.Count,Converter={StaticResource CollectionToCountConverter}}"
  • Related