【问题标题】:Xamarin Forms - populate a custom control when page opensXamarin Forms - 在页面打开时填充自定义控件
【发布时间】:2018-09-08 05:39:42
【问题描述】:

以下是 XAML 页面中的自定义控件,用于在滑块控件中显示图像(除非要求,否则我不会包含该控件的 C# 代码)

    <custom:ImageGallery ItemsSource="{Binding Images}" Grid.Row="1">
                    <custom:ImageGallery.ItemTemplate>
                        <DataTemplate>
                            <Image Source="{Binding Source}" Aspect="AspectFit" >
                                <Image.GestureRecognizers>
                                    <TapGestureRecognizer
                                        Command="{Binding Path=BindingContext.PreviewImageCommand, Source={x:Reference ThePage}}"
                                        CommandParameter="{Binding ImageId}" />
                                </Image.GestureRecognizers>
                            </Image>
                        </DataTemplate>
                    </custom:ImageGallery.ItemTemplate>
                </custom:ImageGallery>
<Button
                Grid.Row="2"
                Text="populate"
                Command="{Binding PopulateCommand}">
            </Button>

当点击按钮时控件被填充。 这是按钮绑定的命令:

public ObservableCollection<GalleryImage> Images
{
    get
    {
       return _images;
    }
}

public ICommand PopulateCommand
{
    get
    {
        return new Command(async () => await PopulateImagesCommand(), () => true);
    }
}

public async Task PopulateImagesCommand()
{
          // adds images to the observable collection 'Images'
}

我宁愿在页面打开后立即进行填充,而不是在单击按钮时进行填充。我试过改变

public ObservableCollection<GalleryImage> Images
{
    get
    {
         return _images;
    }
}

public ObservableCollection<GalleryImage> Images
{
    get
    {
       PopulateImagesCommand();
       return _images;
    }
}

但这显然不起作用。 谁能在这里指出我正确的方向?

【问题讨论】:

    标签: c# xaml xamarin.forms


    【解决方案1】:

    您可以在带有控件的页面首次出现时执行此操作:

    private bool hasAlreadyAppeared;
    protected override void OnAppearing()
    {
        if(!hasAlreadyAppeared) {
            hasAlreadyAppeared = true;
            MyImageGallery.Populate();
        }
    }
    

    当然,您必须公开Populate 方法,并在其中执行PopulateCommand

    【讨论】:

    • 我可以看到你在那儿做什么,并且在调试时 ItemSource 被填充到 OnAppearing 的覆盖中,但它仍然没有在页面中更新,我需要进一步研究这个
    • 您是说您的Images ObservableCollection 被填充,但结果未显示?然后我认为你在其他地方有问题。当页面首次出现时,我总是在OnAppearing 中做这样的事情,所以这绝对应该工作。
    猜你喜欢
    • 2016-12-19
    • 1970-01-01
    • 2020-01-30
    • 2018-04-12
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    相关资源
    最近更新 更多