[英]Xaml Image.Source is not updating in C#
我在更新Xaml中的图像源时遇到了一些麻烦。 我正在制作Windows应用商店应用,然后尝试在C#代码中设置源。 基本上,我的小程序正在做的是让用户选择JPG文件,然后将其复制到AppData文件夹中。 在我的应用中,我希望显示用户上传的图片。 除了我显示图像的那部分以外,其他所有东西都在工作,即使我提供了新的来源,该图像也不想更改。
C#代码:
public sealed partial class MainPage : Page
{
FileOpenPicker pickerSelect;
FileSavePicker pickerSave;
StorageFolder folder;
StorageFile pic;
public MainPage()
{
this.InitializeComponent();
InitializePickers();
InitializeProfilePicture();
}
private async void InitializeProfilePicture()
{
folder = Windows.Storage.ApplicationData.Current.LocalFolder;
pic = await folder.GetFileAsync("profile.jpg");
BitmapImage uri = new BitmapImage(new Uri(pic.Path, UriKind.Absolute));
ProfilePic.Source = uri;
}
private void InitializePickers()
{
pickerSelect = new FileOpenPicker();
pickerSave = new FileSavePicker();
pickerSelect.FileTypeFilter.Add(".jpg");
}
private async void Upload_Click(object sender, RoutedEventArgs e)
{
StorageFile pictureSelect = await pickerSelect.PickSingleFileAsync();
StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
await pictureSelect.CopyAsync(folder, "profile.jpg", NameCollisionOption.ReplaceExisting);
InitializeProfilePicture();
}
}
在方法“ InitializeProfilePicture”中,创建一个新的BitmapImage并将ProfilePic设置为此。 如果我像现在一样从头开始运行InitializeProfilePicture,并且用户选择新图片并将其上传到AppData文件夹,则该代码仅会运行一次(即使图片确实已上传),该图像也不会更改。 如果我从一开始就删除该方法,并将其保留在Button_Click方法中,则将显示新上传的图片。 但是,在ProfilePic设置源之后上传新图片,它不会改变。
Xaml中的图像就是这样
Image Width="480" Height="640" x:Name="ProfilePic" Grid.Row="1" Grid.RowSpan="2"
..还有一个按钮可以运行Upload_Click方法,仅此而已。
知道为什么会这样吗? 它不应该更新吗?
您可以像这样直接从文件中加载BitmapImage:
var imageFile = await picker.PickSingleFileAsync();
var bitmap = new BitmapImage();
using (var stream = await imageFile.OpenReadAsync())
{
await bitmap.SetSourceAsync(stream);
}
ProfilePic.Source = bitmap;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.