I have the below code-behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
ObservableCollection<int> sampleData = new ObservableCollection<int>();
public ObservableCollection<int> SampleData
{
get
{
if (sampleData.Count <= 0)
{
sampleData.Add(1);
sampleData.Add(2);
sampleData.Add(3);
sampleData.Add(4);
}
return sampleData;
}
}
}
My xaml is:
<Window x:Class="Sandbox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox ItemsSource="{Binding Path=SampleData}"/>
</Grid>
</Window>
The list doesn't display the values in the collection (or anything at all). Can someone point out what my mistake is?
Do I need to set the DataContext explicitly? I thought if none is set the control will just use itself as the DataContext.
Yes, you'll need to set the DataContext somehow. It doesn't have a DataContext, because the Window doesn't have a DataContext unless it is set. The ListBox will get the DataContext if you do this in the constructor.
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
Otherwise you can use RelativeSource, ElementName etc. in the Binding but I guess you knew that =)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With