var myListBox = new ListBox(); var myStyle = new Style(typeof(ListBoxItem)); myStyle.Setters.Add(new Setter(ListBoxItem.BackgroundProperty, new SolidColorBrush(Colors.Yellow))); myListBox.Resources.Add("MyListBoxStyle", myStyle); var myList = new List{"Item 1", "Item 2", "Item 3"}; foreach(var item in myList) { var listBoxItem = new ListBoxItem(); listBoxItem.Content = item; listBoxItem.SetResourceReference(ListBoxItem.StyleProperty, "MyListBoxStyle"); myListBox.Items.Add(listBoxItem); }
var myListBox = new ListBox(); var myStyle = (Style)Application.Current.FindResource("MyListBoxItemStyle"); myListBox.ItemContainerStyle = myStyle; var myList = new ListIn this example, we create a new ListBox and retrieve a pre-existing Style from the current Application Resources (assuming it has been previously defined). We set the ItemContainerStyle of the ListBox to this Style. Next, we create a List of strings to use as our data source for the ListBox. We loop through each item in the list and create a new ListBoxItem for each item. We set the Content of the ListBoxItem to the current item in the loop. Finally, we add each ListBoxItem to the ListBox. Package library: PresentationFramework.{"Item 1", "Item 2", "Item 3"}; foreach(var item in myList) { var listBoxItem = new ListBoxItem(); listBoxItem.Content = item; myListBox.Items.Add(listBoxItem); }