【问题标题】:uwp image binding not working with x:Binduwp 图像绑定不适用于 x:Bind
【发布时间】:2017-06-02 18:38:52
【问题描述】:

我正在尝试将 XAML 页面上椭圆内的 imageSource 绑定到 ViewModel 中的 ImageSource 属性,因为我在项目中使用 MVVM 方法。我可以通过断点确认 c# 中的属性获取图像并填充,但由于某种奇怪的原因,它没有显示在 XAML 中,当我在混合中使用 livepropertyExplorer 分析源属性时,ImageSource 中的源显示“0 ”。这是我的代码。

XAML

<Ellipse x:Name="ProfileImage" Style="{StaticResource ProfilePicStyle}">
    <Ellipse.Fill>
        <ImageBrush ImageSource="{x:Bind ViewModel.Banner, Mode=OneWay}" 
                    Stretch="UniformToFill"/>
    </Ellipse.Fill>
</Ellipse>

视图模型

public AllVideosViewModel() : base()
    {
        //var bit = new BitmapImage();
        //bit.UriSource = (new Uri("ms-appx:///Assets/Storelogo.png"));
        //Banner = bit;
        //Above 3 lines were test code and it works perfect and binding works in this case, but I want the binding as coded in the Initialize method below, because I want that image to bind with the thumbnails of the collection.
        Initialize();
    }
private async void Initialize()
    {
        var VideoFiles = (await KnownFolders.VideosLibrary.GetFilesAsync(CommonFileQuery.OrderByName)) as IEnumerable<StorageFile>;

        foreach (var file in VideoFiles)
        {
            <...some code to fill grid view on the same XAML page which works perfect...>
            Banner = await FileHelper.GetDisplay(file);//this method returns Image just fine because I am using the same method to display thumbnails on the same XAML page which work fine.
        }

    }

提前致谢。

更新示例项目

sample project to test on github

【问题讨论】:

  • “此方法返回图像 ...”。实际上,它应该返回一个 ImageSource(或像 BitmapImage 这样的派生类型)。 Banner 属性的类型是什么?
  • banner属性类型为ImageSource,GetDisplay方法返回BitmapImage
  • 方法很好,因为我指定我使用相同的方法在同一页面上用缩略图填充我的 gridview
  • 改成本地图片,行吗?
  • 是的,正如我在代码中提到的,如果我将它绑定到资产文件夹中的图像,那么它可以正常工作@Justin XL

标签: c# image xaml binding uwp-xaml


【解决方案1】:

我在你的代码中注意到了一些事情。

  1. 您的MainViewModel 需要实现INotifyPropertyChanged 并且您的Banner 属性需要引发属性更改事件。这就是您在 UI 上看不到任何图像的原因。
  2. 您应该使用 await bit.SetSourceAsync() 而不是 bit.SetSourceAsync(),因为它不会阻塞 UI 线程。
  3. 由于您没有使用Image 控件而是直接使用ImageBrush,因此您应该将解码大小设置为您需要的大小,这样就不会在那里浪费内存。请注意Image 控件会自动为您执行此操作。

        bit = new BitmapImage
        {
            DecodePixelWidth = 48,
            DecodePixelHeight = 48
        };
    

希望这会有所帮助!

【讨论】:

  • 为什么需要提供 Inotify 属性? x:Bind 不是应该自动执行此操作的一种方式吗?我的意思是,如果不是,那么 X:Bind with Mode "oneway" 的功能是什么?
  • 否... x:Bind 只为您提供编译时绑定,它为您提供比传统绑定更好的性能。没有其他任何改变。 x:与oneway绑定功能是周年纪念更新中的新功能。 docs.microsoft.com/en-us/windows/uwp/xaml-platform/…
  • 在函数绑定中用作参数时,您仍然需要带有 INotifyPropertyChanged 的​​属性,否则它如何知道何时重新评估?
  • 在这种情况下,我直接绑定到视图模型中的属性,是的,您的解决方案适用于实现的 Inotify 属性,但我仍然不清楚 oneway 的功能是什么,如果我们仍然需要实现Inotify,是的,我项目的最低目标是 Anniversay 更新
  • 我正在更改函数中特定属性的值,这就是我需要 Inotify 的原因吗?
猜你喜欢
  • 2017-02-07
  • 1970-01-01
  • 2017-07-13
  • 2021-04-15
  • 2016-11-26
  • 2015-12-11
  • 2020-01-29
  • 2018-09-17
  • 2020-08-31
相关资源
最近更新 更多