uwp图像绑定无法使用x:绑定

时间:2017-06-02 18:38:53

标签: c# image xaml binding uwp-xaml

我正在尝试将我的XAML页面上的椭圆内的imageSource绑定到我的ViewModel中的ImageSource属性,因为我在我的项目中使用MVVM方法。我可以通过断点确认c#中的属性获取图像并被填充,但由于某些奇怪的原因它不会出现在XAML中,当我在混合中使用livepropertyExplorer分析source属性时,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

1 个答案:

答案 0 :(得分:2)

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

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

        bit = new BitmapImage
        {
            DecodePixelWidth = 48,
            DecodePixelHeight = 48
        };
    
  4. 希望这有帮助!

相关问题