首页 > 解决方案 > Xamarin Forms 更改 CollectionView 中元素的大小

问题描述

我有这个代码:

<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>

现在我希望我能做到:

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;
    };
}

但我得到一个错误:

TemplateImage当前上下文中不存在该名称

现在我已经在我的 xaml 中用这一行声明了它:

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

现在如何在 C# 中更改 CachedImage 的大小?

标签: c#xamarinxamarin.formsxamarin.androidxamarin.ios

解决方案


正确的方法是在XAMLHeightRequest中绑定您的属性,如下所示CachedImage

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

wishedHeight视图模型中的属性在哪里。

注意不能直接使用

HeightRequest="{Binding wishedHeight}" 

因为 wishedHeight 不是TemplateSource您的 CachedImage 绑定到的类的一部分!


推荐阅读