2014-12-04 141 views
0

我試圖讓用戶在視圖中加載圖像。將圖像從viewmodel加載到Caliburn.Micro視圖中

我的主視圖:

<UserControl x:Class="TestApplication.Views.MainView" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d"> 
    <Grid> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="*" /> 
      <ColumnDefinition Width="0.3*" /> 
     </Grid.ColumnDefinitions> 

     <Image 
      Grid.Column="0" 
      Stretch="Uniform" 
      x:Name="Preview"> 
      <Image.Source> 
       <BitmapImage UriSource="pack://application:,,,/Resources/placeholder.jpg" /> 
      </Image.Source> 
     </Image> 

     <ContentControl 
      Grid.Column="1" 
      x:Name="ImageManagement" /> 

    </Grid> 
</UserControl> 

我的主視圖模型:

namespace TestApplication.ViewModels 
{ 
    using System; 
    using System.ComponentModel.Composition; 
    using System.Windows.Controls; 
    using Caliburn.Micro; 
    using PropertyChanged; 
    using TestApplication.Events; 

    [ImplementPropertyChanged] 
    [Export(typeof(MainViewModel))] 
    public class MainViewModel : PropertyChangedBase, IHandle<FileSelectedEvent> 
    { 
     private readonly IEventAggregator events; 

     [ImportingConstructor] 
     public MainViewModel(IEventAggregator events) 
     { 
      this.events = events; 
      this.events.Subscribe(this); 

      this.ImageManagement = new ImageManagementViewModel(events); 
     } 

     public ImageManagementViewModel ImageManagement { get; set; } 

     public Image Preview { get; set; } 

     public void Handle(FileSelectedEvent message) 
     { 
      // load the selected image 
     } 
    } 
} 

圖像佔位符不顯示,而窺探甚至沒有看到它。

此外,通過實例化一個BitmapImage並在Handle方法將其設置爲Preview.Source加載圖像時...的Preview屬性爲null,如果我先初始化它,它從來沒有任何顯示。

PropertyChanged通過Fody進行處理。

+0

佔位符很可能是無效的URI。無法爲您調試。預覽沒有綁定到你包含的代碼中的任何東西,所以我不知道這個魔法應該如何工作...... – Will 2014-12-04 18:03:18

+0

Image的默認約定在Source屬性中,並且由Loaded觸發。我敢打賭,你可能需要使圖像成爲URI或字符串值,而不是實際的圖像控件。 – mvermef 2014-12-04 18:31:53

+0

我認爲@Will對於包uri來說是對的,我不認爲你需要它開始。只要將Source設置爲''''''一旦觸發屬性更改,它應該按照慣例綁定。 – mvermef 2014-12-04 18:42:41

回答

0

感謝@Will和@mvermef,我找到了我的答案。

佔位符URL無效,但它在沒有pack://部分的情況下工作。不過,我喜歡它,因爲它明確表示它是一種資源而不是文件。

真正的問題是,的確,Caliburn.Micro實際上並未綁定到控件,而是屬於Source屬性。切換到該解決的問題:

<Image 
     Grid.Column="0" 
     Stretch="Uniform" 
     Source="{Binding PreviewUrl}" /> 

和視圖模型:

[ImportingConstructor] 
    public MainViewModel(IEventAggregator events) 
    { 
     this.events = events; 
     this.events.Subscribe(this); 

     this.ImageManagement = new ImageManagementViewModel(events); 
     this.PreviewUrl = "pack://application:,,,/Resources/placeholder.jpg"; 
    } 

    public String PreviewUrl { get; set; } 

    public void Handle(FileSelectedEvent message) 
    { 
     this.PreviewUrl = message.FilePath; 
    }