以下是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;
}
}
但这显然不起作用。 谁能指出我在这方面的正确方向?
答案 0 :(得分:1)
首次显示控件的页面时,您可以执行此操作:
private bool hasAlreadyAppeared;
protected override void OnAppearing()
{
if(!hasAlreadyAppeared) {
hasAlreadyAppeared = true;
MyImageGallery.Populate();
}
}
当然,您必须公开Populate
方法,并在其中执行PopulateCommand
。