2

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>

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.