Home > Enterprise >  How to make ListBox show different Elements (which are in a List) in wpf
How to make ListBox show different Elements (which are in a List) in wpf

Time:07-31

Suppose I have a list which contains some elements and texts:

     public MainWindow()
     {
         InitializeComponent();

         TextBlock t = new TextBlock();
         t.Text = "Hello World!";

         Ellipse e = new Ellipse();
         e.Width = 100;
         e.Height = 100;
         e.Fill = new SolidColorBrush(Colors.Yellow);

         Rectangle r = new Rectangle();
         r.Width = 70;
         r.Height = 40;
         r.Fill = new SolidColorBrush(Colors.Blue);

         List<UIElementItem> items = new List<UIElementItem>();
         items.Add(new UIElementItem() { uiElement = t, Text = "This is a TextBlock: " });
         items.Add(new UIElementItem() { uiElement = e, Text = "This is an Ellipse: " });
         items.Add(new UIElementItem() { uiElement = r, Text = "This is a Rectangle: " });
         lbListBox.ItemsSource = items;
     }

 }

 public class UIElementItem
 {
     public UIElement uiElement { get; set; }
     public string Text { get; set; }
 }

This is the ListBox in XAML:

<ListBox Name="lbListBox" HorizontalContentAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Margin="0,2" Orientation="Horizontal">
                <TextBlock Text="{Binding Text}"/>
                <??? = "{Binding uiElement}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I want to make the ListBox show the texts and the elements.

The TextBlock Text="{Binding Text}" will show the text but how to show the element? How to bind?

CodePudding user response:

You could use a ContentPresenter

<ContentPresenter Content="{Binding uiElement}" />

This would show the UI Elements. The complete ItemTemplate would look like

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="0,2" Orientation="Horizontal">
                        <TextBlock Text="{Binding Text}"/>
                        <ContentPresenter Content="{Binding uiElement}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
  • Related