views:

211

answers:

2

I know this has been asked different ways several times, but I'm just not getting it. Why don't I see my test strings in the listbox?

.cs

 public partial class Window1 : Window
 {
    public ObservableCollection<string> myList = new ObservableCollection<string>();

    public Window1()
    {
        InitializeComponent();

        myList.Add("test1");
        myList.Add("test2");
    }
}

.xaml

<Window x:Class="WpfApplication.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300"
    x:Name="thisWindow">
    <Grid>
        <ListBox Name="MyListBox" ItemsSource="{Binding myList, ElementName=thisWindow}"/>
    </Grid>
</Window>
+1  A: 

Because your "myList" is a field. WPF binding only works with properties. Change your list's declaration to:

private ObservableCollection<string> _myList = new ObservableCollection<string>();

public ObservableColelction<string> myList { get { return _myList; } }
Matt Hamilton
yup, I'm obviously new to this. Thanks.
Damon A.
A: 

Try it this way:

public Window1()
{
    InitializeComponent();

    myList.Add("test1");
    myList.Add("test2");

    this.DataContext = myList;
}

and then in XAML:

<ListBox Name="MyListBox" ItemsSource="{Binding}"/>
bitbonk