Search code examples
xamlxamarin.formsdatatrigger

Check if last list item is equal to length Xamarin Forms binding


I am trying to hide last Grid column. I'm trying to do it with DataTrigger, this is how my trigger looks like:

            <ResourceDictionary>
               <Style x:Key="HideLastVerticalLine" TargetType="BoxView">
                  <Style.Triggers>
                    <DataTrigger
                        Binding="{Binding Items, Path=Items.LastOrDefault}"
                        TargetType="BoxView"
                        Value="{Binding Items.Length}">
                        <Setter Property="IsVisible" Value="False" />
                    </DataTrigger>
                  </Style.Triggers>
               </Style>
           </ResourceDictionary>

           <BoxView Style="{StaticResource HideLastVerticalLine}" Grid.Column="1" HeightRequest="100" WidthRequest="1" BackgroundColor="Black"/>

I'm applying this DataTrigger to a BoxView, which contains a vertical line separator (I want something as Trim(), just to remove last separator line.

How can I do it?


Solution

  • You can use a DataTemplateSelector to achieve this.

    The sample is here.

    Create two DataTemplates, one for LastViewCell and one for other ViewCells:

    public class PersonDataTemplateSelector : DataTemplateSelector
    {
        public DataTemplate NormalTemplate { get; set; }
    
        public DataTemplate LastCellTemplate { get; set; }
    
        protected override DataTemplate OnSelectTemplate (object item, BindableObject container)
        {
    
            var lastItem = Items.LastOrDefault();
    
            return lastItem = item ? LastCellTemplate : NormalTemplate;
        }
    }
    

    Choose to use which DataTemplate by checking if the item is last Item.