[英]C# UWP Change Image-Source in ListView-Binding
我自己有一个 C# UWP 解决方案,我已经定义了特殊清单broadFileSystemAccess
,所以我可以直接从我的电脑访问所有文件。
我通过将ListView
的ItemsSource
设置为ObservableCollection<someModel>
变量来填充ListView
(下面有更多详细信息)。 点击它后,我想改变它。
在 class someModel
,我将图像的路径和内容设置为BitmapImage
。 我这样做是因为该文件位于我的 PC 上的某个路径上,例如E:\pix\some path\image.jpg
,然后将此文件读入BitmapImage
,以便稍后将其绑定为图像源。 这是超级慢和低效的,但它现在可以工作,我将来会改变它。
class someModel
{
public string ImagePath { get; set; }
public BitmapImage ImageContent { get; set; }
}
和我的 XAML 图像:
<Image DataContext="{x:Bind Mode=TwoWay}" Source="{x:Bind ImageContent, Mode=OneWay}" Width="400" Stretch="UniformToFill" Tapped="lvImageEditImage_Tapped" />
我的 function lvImageEditImage_Tapped
:
var picker = new Windows.Storage.Pickers.FileOpenPicker
{
ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail,
SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary
};
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
var item = (sender as Image).DataContext as someModel;
item.ImagePath = file.Path;
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
await bitmapImage.SetSourceAsync(fileStream);
}
item.ImageContent = bitmapImage;
}
虽然我现在获得了路径,但图像内容bitmapImage
不会更改查看的图像。
为什么图像没有更新到新的BitmapImage
内容?
请在数据 model 中添加INotifyPropertyChanged
接口。
public class someModel:INotifyPropertyChanged
{
private BitmapImage _imageContent;
public BitmapImage ImageContent
{
get => _imageContent;
set
{
_imageContent = value;
OnPropertyChanged();
}
}
public string ImagePath { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
继承INotifyPropertyChanged
接口后,可以使用{x:Bind ImageContent, Mode=OneWay}
完成绑定。 当数据源被修改时,会通知UI界面发生变化。
此致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.