MG_REX
MG_REX

Reputation: 139

Add items to custom ListBox

I've this template of ListBoxItem that contains an Image and TextBlock. How to add an Item to this ListBox from code?

<ListBox Name="listBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" >
                <Image Source="{Binding}" Width="16" />
                <TextBlock Text="{Binding}" Margin="5,0,0,0" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 2

Views: 92

Answers (1)

Krishna Veeramachaneni
Krishna Veeramachaneni

Reputation: 2141

I am assuming you will want to have a class which has imagesource and text properties in the lines of

public class TestClass()
{
    public string ImageSrc {get; set;}
    public string DisplayText {get; set;}
}

Add the objects to your collection

listBox.Items.Add(new TestClass() { ImageSrc = "blahblah", DisplayTest = "Test Display Text" });

and so on

Then you can use xaml in the lines of

<ListBox Name="listBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" >
                <Image Source="{Binding ImageSrc}" Width="16" />
                <TextBlock Text="{Binding DisplayText}" Margin="5,0,0,0" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 2

Related Questions