0
votes

I have this code:

<ContentPage.Content>
    <StackLayout HorizontalOptions="Fill" Padding="15">
        <Frame IsClippedToBounds="True" HeightRequest="45" CornerRadius="5" Padding="0" BackgroundColor="Transparent">
            <Entry Placeholder="Search" ReturnType="Done" PlaceholderColor="Gray" x:Name="txtSearch" Margin="5,0,0,0" TextColor="White" />
        </Frame>

        <CollectionView ItemsSource="{Binding sourceList}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"
                    Span="2" />
            </CollectionView.ItemsLayout>
                <CollectionView.ItemTemplate>
                    <DataTemplate>

                        <ff:CachedImage
                    Source="{Binding Source}"
                    VerticalOptions="Center"
                    HorizontalOptions="Fill"
                    x:Name="TemplateImage" />

                    </DataTemplate>
                </CollectionView.ItemTemplate>
        </CollectionView>
    </StackLayout>
</ContentPage.Content>

Now I hoped that I could just do:

public TemplateList()
{
    InitializeComponent();

    var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
    var width = mainDisplayInfo.Width;
    var density = mainDisplayInfo.Density;
    var ScaledWidth = width / density;

    var WidthHeight = (ScaledWidth - (3 * 10)) / 2;

    SizeChanged += (s, a) =>
    {
        TemplateImage.HeightRequest = WidthHeight;
        TemplateImage.WidthRequest = WidthHeight;
    };
}

But i get an error:

The name TemplateImage does not exist in the current context

Now I have declared it in my xaml with this line:

<ff:CachedImage
    Source="{Binding Source}"
    VerticalOptions="Center"
    HorizontalOptions="Fill"
    x:Name="TemplateImage" />

Now how can I change the size of that CachedImage in C#?

2
I would use DataBinding to bind WidthRequest and HeightRequest of the CachedImage to the data objects within the collection you reference as your ItemsSource.Mouse On Mars

2 Answers

0
votes

The right approach would be to bind the HeightRequest property of your CachedImage in XAML as follows

<ff:CachedImage
    Source="{Binding Source}"
    HeightRequest="{Binding Source=MyViewModel Path=wishedHeight}"
    VerticalOptions="Center"
    HorizontalOptions="Fill" />

where wishedHeight is a property in your view model.

Note that you can not use directly

HeightRequest="{Binding wishedHeight}" 

since wishedHeight is not part of the TemplateSource class, to which your CachedImage is bound!

0
votes

Try using ItemSizingStrategy="MeasureFirstItem" if all your items have the same height. Refer here - https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/layout#item-sizing