Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say, for instance, I have the following extremely simple window:

<Window x:Class="CalendarGenerator.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1"
        Height="300"
        Width="447">
  <Grid>
    <ListBox Margin="12,40,0,12"
             Name="eventList"
             HorizontalAlignment="Left"
             Width="134" />
  </Grid>
</Window>

And a simple list defined as:

List<String> ListOfNames = new List<String>();

And let's assume that the list has several names in it. How would I go about binding the List to the ListBox using as much code-behind as possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
116 views
Welcome To Ask or Share your Answers For Others

1 Answer

First you'd need to give your ListBox a name so that it's accessible from your code behind (edit I note you've already done this, so I'll change my example ListBox's name to reflect yours):

<ListBox x:Name="eventList" ... />

Then it's as simple as setting the ListBox's ItemsSource property to your list:

eventList.ItemsSource = ListOfNames;

Since you've defined your "ListOfNames" object as a List<String>, the ListBox won't automatically reflect changes made to the list. To get WPF's databinding to react to changes within the list, define it as an ObservableCollection<String> instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...