繁体   English   中英

如何将我的新图像的路径作为字符串保存到数据库中,以便在创建新记录后我可以看到我选择的图像?

[英]How to save the path of my new image to the database as a string so that after creating a new record I can see the image that I selected?

我有一个 model 记录,我想在选择照片时保存我的图像路径:

public class Record {
...
    public string ImageFile { get; set; }
}

我有一个 RecordEntry.xaml:

<Image x:Name="FileImage" 
            Source="{Binding Path=ImageFile, Converter={StaticResource ImageSourceConverter}}"
            WidthRequest="200"
            HeightRequest="200"
            HorizontalOptions="Center" 
            VerticalOptions="Center"/>
<Button Text="Pick Photo"
            BackgroundColor="Teal" 
            TextColor="White" 
            FontSize="40" 
            Clicked="PickPhotoClicked"/>

所以,我有一个 RecordEntry.cs,我在其中使用 Plugin.Media 挑选照片:

 private async void PickPhotoClicked(object sender, EventArgs e)
    {
        await CrossMedia.Current.Initialize();
        if (!CrossMedia.Current.IsPickPhotoSupported)
        {
            await DisplayAlert("No Pick Photo", ":( No Pick Photo available", "OK");
            return;
        }

        _mediaFile = await CrossMedia.Current.PickPhotoAsync();
        if (_mediaFile == null)
        {
            return;
        }

        await DisplayAlert("File Path", _mediaFile.Path, "OK");

        FileImage.Source = ImageSource.FromStream(() =>
        {
            return _mediaFile.GetStream();
        });
    }

选择照片后,我想保存路径并将其绑定到ImageFile ,并且我想在再次打开此记录时看到我的照片。

您可以使用Xamarin.Essentials: Preferences to store and read the File Path

存储路径:

private async void PickPhotoClicked(object sender, EventArgs e)
{

    //...
    await DisplayAlert("File Path", _mediaFile.Path, "OK");

    //Store your path here
    Preferences.Set("my_File_Path", _mediaFile.Path);

    FileImage.Source = ImageSource.FromStream(() =>
    {
        return _mediaFile.GetStream();
    });
}

使用路径: ,如果存在则使用ImageFile

public Record _record{ get; set; }

protected override void OnAppearing()
{
    base.OnAppearing();

    _record = new Record();
    string myValue = Preferences.Get("my_File_Path", "default_value");
    _record.ImageFile = myValue;

    BindingContext = _record;
}

并在您的ImageSourceConverter中,将imagePath转换为ImageSource

public class myImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var path = (string)value;
        return ImageSource.FromFile(path);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

在这里上传了一个样本,如果您有任何问题,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM