Gör så här: Binda en ListBox till data

En programutvecklare kan skapa ListBox kontroller utan att ange innehållet i varje ListBoxItem separat. Du kan använda databindning för att binda data till enskilda objekt.

I följande exempel visas hur du skapar en ListBox som fyller i de ListBoxItem elementen genom databindning till en datakälla med namnet Colors. I det här fallet är det inte nödvändigt att använda ListBoxItem taggar för att ange innehållet i varje objekt.

Exempel

<Canvas.Resources>
  <src:myColors x:Key="Colors"/>
</Canvas.Resources>
<ListBox Name="myListBox" HorizontalAlignment="Left" SelectionMode="Extended" 
      Width="265" Height="55" Background="HoneyDew" SelectionChanged="myListBox_SelectionChanged"
      ItemsSource="{Binding Source={StaticResource Colors}}" IsSynchronizedWithCurrentItem="true">
</ListBox>

Se även