【问题标题】:C# UWP Change Image-Source in ListView-BindingC# UWP 在 ListView-Binding 中更改图像源
【发布时间】:2020-02-12 13:32:18
【问题描述】:

我自己有一个 C# UWP 解决方案,我已经定义了特殊清单 broadFileSystemAccess,所以我可以直接从我的 PC 访问所有文件。

我通过将ListViewItemsSource 设置为ObservableCollection<someModel> 变量来填充ListView(更多详细信息如下)。点进去之后,我想改一下。

someModel 类中,我将图像的路径和内容设置为BitmapImage。我这样做是因为该文件位于我 PC 上的某个路径上,例如E:\pix\some path\image.jpg,然后把这个文件读入BitmapImage,这样我以后就可以把它绑定为Image源了。这是超级慢和低效的,但它现在有效,我会在未来改变它。

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" />

我的函数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 内容?

【问题讨论】:

    标签: c# image listview uwp


    【解决方案1】:

    请将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界面发生变化。

    最好的问候。

    【讨论】:

      猜你喜欢
      • 2016-09-23
      • 2016-03-29
      • 2017-02-07
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多