2013-05-06 19 views
1

我想通過ItemsTemplate將一個列表框綁定到自定義「文檔」對象的集合,但在嘗試將圖像綁定到Document.ImageResourcePath屬性時遇到問題。這是我的標記<Image>源不能在綁定

<ListBox Name="lbDocuments"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <StackPanel> 
         <Image Source="{Binding Path=ImageResourcePath}" 
            Margin="5,0,5,0"/> 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate>     
</ListBox> 

這是我的載入事件的窗體有列表框。

private void Window_Loaded_1(object sender, RoutedEventArgs e) 
    { 

     List<Objects.Document> docs = Objects.Document.FetchDocuments(); 
     lbDocuments.ItemsSource = docs; 
    } 

我的文檔類包含一個字符串,位於我的資源文件夾根據文件擴展的資源的圖像。

例如(這是文檔類中的一個case語句的一部分)

case Cache.DocumentType.Pdf: 
    this.ImageResourcePath = "/JuvenileOrganizationEmail;component/Resources/pdf_icon.jpg"; 
    break; 

當窗口加載我得到了我的列表框中一無所有時,它必然要23非常清楚的文檔類型。我可能做錯了什麼?

+1

已經設置您的窗戶'DataContext'(雖然可如果你正在做MVVM建議採用單獨的視圖模型類)? – 2013-05-06 04:18:12

+1

出於調試的目的,嘗試在圖像上設置固定的寬度和高度(以防它們呈現爲零大小時),並向綁定到相同字段的StackPanel添加TextBlock或類似物,以便您可以看到是否正確綁定了數據。同時檢查輸出窗口是否有綁定錯誤。 – 2013-05-06 04:20:13

+0

@DavidCummins我剛剛添加了一個文本塊並彈出,但即使使用硬編碼的20x20,圖像仍然不顯示。 – Adrian 2013-05-06 04:23:38

回答

1

使用ObservableCollection而不是List,並將參考「級別」設置爲您的Window

ObservableCollection<Objects.Document> _docs; 

確保在窗口的Ctor中設置了DataContext。

public Window() 
{ 
    _docs = new ObservableCollection<Objects.Document>(Objects.Document.FetchDocuments()); 
    this.DataContext = this; 
} 

然後,你可以更新你的窗口已加載事件:

private void Window_Loaded_1(object sender, RoutedEventArgs e) 
    { 
     lbDocuments.ItemsSource = _docs; 
    } 

或者替代解決方案,將直接綁定ListBox的的ItemsSource到集合的公共屬性。這是假設Ctor(上圖)仍在使用。

<ListBox Name="lbDocuments" ItemsSource={Binding Docs}> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <StackPanel> 
         <Image Source="{Binding Path=ImageResourcePath}" Margin="5,0,5,0"/> 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate>     
</ListBox> 

在你Window.cpp文件

public ObservableCollection<Objects.Document> Docs 
    { 
    get { return _docs; } 
    } 
+0

問題解決了。我的問題是** this.DataContext = this **,而不是我正在使用的。 this.lbDocuments.DataContext = docs – Adrian 2013-05-06 04:46:42

+0

@阿德里安太棒了!很高興它的工作。 – 2013-05-06 04:48:38