Reputation: 638
I really looked hard. There seems to be something I am missing. Using .net 4.5.
Here's my XAML:
<Window x:Class="a.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:a"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox x:Name="myListBox" HorizontalAlignment="Left" Height="201" Margin="144,33,0,0" VerticalAlignment="Top" Width="115" ItemsSource="{Binding (local:myClass.myStaticList)}"/>
<Button Content="Button" HorizontalAlignment="Left" Height="48" Margin="282,247,0,0" VerticalAlignment="Top" Width="150" Click="Button_Click"/>
</Grid>
</Window>
and here's the code behind:
using System.Collections.ObjectModel;
using System.Windows;
namespace a
{
public class myClass
{
public static ObservableCollection<string> myStaticList { get; set; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
myListBox.Items.Add("aaa");
myListBox.Items.Add("bbb");
myListBox.Items.Add("ccc");
myListBox.Items.Add("ddd");
myListBox.Items.Add("eee");
myListBox.Items.Add("rrr");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
<--- Breakpoint here
}
}
}
Real simple.
The button is used only to pause the running with a breakpoint and see whether the data was introduced from myListBox
to myControl.myList
.
It doesn't. myList
remains null. What am I missing?
Help please! TIA
Upvotes: 2
Views: 4898
Reputation: 13188
You have to create an instance and add data to your ObservableCollection
, not to the ListBox
that is binding to it.
MainWindow.cs :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
myClass.myStaticList = new ObservableCollection<string>();
myClass.myStaticList.Add("aaa");
myClass.myStaticList.Add("bbb");
myClass.myStaticList.Add("ccc");
myClass.myStaticList.Add("ddd");
myClass.myStaticList.Add("eee");
myClass.myStaticList.Add("fff");
}
}
XAML :
<Grid>
<ListBox x:Name="ListBox1" Margin="0" ItemsSource="{Binding myStaticList}">
<ListBox.DataContext>
<local:myClass/>
</ListBox.DataContext>
</ListBox>
</Grid>
Result:
Upvotes: 3