1

我正在尝试通过 ItemsTemplate 将列表框绑定到自定义“文档”对象的集合,但是在尝试将图像绑定到 Document.ImageResourcePath 属性时遇到问题。这是我的标记

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

我的 Document 类根据文档扩展名将字符串保存到位于我的资源文件夹中的资源图像。

例如(这是文档类中 case 语句的一部分)

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

当窗口加载时,当它绑定到 23 个完美的文档类型时,我的列表框中什么也没有。我可能做错了什么?

4

1 回答 1

1

使用 anObservableCollection而不是 a List,并为您的Window.

ObservableCollection<Objects.Document> _docs; 

确保在 Window 的 Tor 中设置了 DataContext。

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

然后,您可以更新您的 Window Loaded 事件:

   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 文件中(不过,如果您正在执行 MVVM,可能会建议使用单独的 ViewModel 类)

  public ObservableCollection<Objects.Document> Docs 
  {
     get { return _docs; }
  }
于 2013-05-06T04:27:31.127 回答