Setting to DataContext not reflecting in Listbox
I have a ViewModel and i am setting an instance of it to DataContext.In xaml i have binded the Listbox itemsource to an observable collection in ViewModel.But when i run the program nothing appears in listbox.What may be the Reason.
My ViewModel class:
public class ViewModel
{
public ObservableCollection<Data> _collectionData = new ObservableCollection<Data>();
-----
-----
}
Xaml:
ListBox Name="myListBox" Margin="8,113,8,8" ItemsSource="{Binding _collectionData}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<Border BorderThickness="3" BorderBrush="#A5FFFFFF" Width="80" Margin="0,20,0,20" Height="60">
<Image Source="{Binding ImageUrl, Mode=OneWay}" VerticalAlignment="Stretch" Margin="0,0,0,0" Width="80" Height="60" Stretch="Fill" />
开发者_StackOverflow中文版 </Border>
<TextBlock TextWrapping="Wrap" Text="{Binding Title}" FontSize="40" FontWeight="Normal" VerticalAlignment="Center" Margin="30,0,0,0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Constructor of main page:
ViewModel vm = new ViewModel();
this.DataContext = vm;
But when i give myListBox.ItemsSource = vm._collectionSplashData;
it works .what may be the reason?
Make property instead of field
see Binding Sources Overview
Applying both ItemsSource and Datacontext not needed.
精彩评论