2017-06-02 97 views
0

我想我的XAML页面上的椭圆内的imageSource绑定到我的ViewModel中的ImageSource属性,因为我在我的项目中使用MVVM方法。我可以通过断点来确认c#中的属性获取图像并被填充,但由于某些奇怪的原因,它不会显示在XAML中,并且当我在混合中使用livepropertyExplorer分析源属性时,ImageSource中的源显示“0 ”。这是我的代码。uwp图像绑定不工作与x:绑定

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. 
     } 

    } 

在此先感谢。

UPDATE示例项目

sample project to test on github

+0

“此方法返回图像...”。实际上,它应该返回一个ImageSource(或像BitmapImage这样的派生类型)。 Banner属性的类型是什么? – Clemens

+0

横幅属性的类型是ImageSource和方法GetDisplay返回BitmapImage – touseef

+0

方法是好的,因为我指定我使用相同的方法来填充我的gridview缩略图在同一页上 – touseef

回答

2

我已经在你的代码发现有几件事情。

  1. MainViewModel需要实现INotifyPropertyChanged和你Banner属性需要提高的属性更改事件。这就是为什么你没有看到任何图像显示在用户界面上。
  2. 您应该使用await bit.SetSourceAsync()而不是bit.SetSourceAsync(),因为它不会阻塞UI线程。
  3. 由于您没有直接使用Image控制器,而是使用ImageBrush,因此您应该将解码大小设置为您需要的大小,以免浪费内存。请注意,Image控件会自动为您执行此操作。

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

希望这有助于!

+0

为什么我需要提供Inotify属性?不x:绑定一种方式应该自动执行此操作?我的意思是,如果不是,那么X的功能:与模式“单向”绑定? – touseef

+1

否... x:绑定仅为您提供编译时绑定,使您可以比传统绑定获得更好的性能。没有其他改变。 x:单向绑定功能是周年更新中的新功能。 https://docs.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension#functions-in-binding-paths –

+1

当它们用作参数时,您仍然需要使用INotifyPropertyChanged的属性在函数绑定中,否则它将如何知道何时重新评估? –