将用作按钮的图像替换为另一个图像

时间:2017-02-24 20:35:35

标签: xamarin xamarin.forms

我正在使用 xamarin.forms 构建联系簿应用程序。在此,我想提供一个图像作为按钮,用于从设备存储上传联系人的照片。完成照片选择后,我希望用户选择的图像替换之前用作按钮的图像。

Contact.xaml:

<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell>
            <StackLayout Padding="10,5,0,5">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="50" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <StackLayout BackgroundColor="Fuchsia"  Grid.Row="0" Grid.Column="0">
                        <Image Source = "camera.png" HeightRequest="30" VerticalOptions="FillAndExpand" 
                                BackgroundColor="Lime" x:Name="imageButton"/>
                        <Image x:Name="image" />
                        <Image.GestureRecognizers>
                            <TapGestureRecognizer Tapped="OnImageTapped" />
                        </Image.GestureRecognizers>
                    </StackLayout>
                    <Entry Grid.Row="0" Grid.Column="1" HorizontalTextAlignment="Center"
                            TextColor="#151431" x:Name="ContactEntry" FontSize="Medium"
                            WidthRequest="400"/>
                </Grid>
            </StackLayout>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>

Contacts.xaml.cs

async void OnImageTapped(object sender, EventArgs args)
{
    var image = sender as Image;
    if (!CrossMedia.Current.IsPickPhotoSupported)
    {
        await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
        return;
    }
    var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
    {
        PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
    });
    if (file == null)
        return;
    image.Source = ImageSource.FromStream(() =>
          {
              var stream = file.GetStream();
              file.Dispose();
              return stream;
          });
}

0 个答案:

没有答案