2013-05-06 54 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