如何访问列表框的项目

时间:2015-04-05 08:25:35

标签: c# wpf listbox

我有一个像这样的列表框

<ListBox x:Name="lbAlbumSelect">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                            <Button>
                                    <Button.Content>
                                        <StackPanel>
                                        <Image />
                                            <TextBlock TextWrapping="Wrap" 
                                                           Text="{Binding album_name}" />
                                        </StackPanel>
                                    </Button.Content>
                                </Button>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
</ListBox>

我想以编程方式访问每个Image并设置其Source。我试图像这样导航列表框

foreach (Button btn in lbAlbumSelect.Items)
           {
               StackPanel stack=btn.Content;
               Image image=stack.Children.ElementAt(0) as Image;
               //every ListBoxItem is binded to a clsAlbums object that contains various data, 
               //also the name of the image file, but not the path.
               string pathImg = @"/Assets/Images/" + (btn.DataContext as clsAlbums).album_img; 
               LoadImage(pathImg, image); //function that sets image source to path img
           }

但是在foreach条款中给了我一个Invalid Cast Exception

有更快,更正确的方法吗?

2 个答案:

答案 0 :(得分:1)

理想情况下,您应该将图像源绑定到控件。在clsAlbums类中添加一个附加属性,该类可以绑定到Image源。

public class clsAlbum
{
    public string album_name { get; set; }
    public string album_img { get; set; }
    public string album_img_src 
    {
        get
        {
             return @"/Assets/Images/" + album_img;
        }
    }
}

现在将此附加属性album_img_src绑定到您的xaml。

    <ListBox x:Name="lbAlbumSelect">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button>
                <Button.Content>
                    <StackPanel>
                        <Image Source="{Binding album_img_src}"/>
                        <TextBlock TextWrapping="Wrap" 
                                                    Text="{Binding album_name}" />
                    </StackPanel>
                </Button.Content>
            </Button>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

答案 1 :(得分:1)

  1. 该项目实际上是ListBoxItem。在你的情况下,Button是ListBoxItem的内容,Button的内容是StackPanel,Image是StackPanel的子项。因此,您需要以某种方式遍历可视树,例如,您可以使用Linq对可视化树进行遍历。 http://www.codeproject.com/Articles/63157/LINQ-to-Visual-Tree

  2. 访问datatemplate中元素的最简单方法是从它的加载或初始化事件中获取:

  3. 这里:

    <Image Loaded="Image_Loaded" />
    
    void Image_Loaded(object sender, EventArgs e){
        var image =(Image)sender;
    
    1. 尽量避免访问datatemplates中的元素。使用ViewModel,转换器,使用行为,数据触发器或提取datatemplate来分离UserControl,90%的时间可以更好地实现目标