Reputation: 1289
I am very new to Windows Phone development, and I have been trying to bind a list to the LongListSelector included in the base Pivot application, but with no success.
Here's the constructor of the main page (where the binding occurs):
public MainPage()
{
InitializeComponent();
List<int> testList = new List<int>();
testList.Add(0);
testList.Add(1);
testList.Add(2);
listDisplay.ItemsSource = testList;
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
And here's the XAML for the LongListSelector:
<vm:MainViewModel
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:PivotApp2.ViewModels"
SampleProperty="Sample Text Property Value">
<vm:MainViewModel.Items>
<vm:ItemViewModel x:Name="listModel" LineOne="{Binding Source}"/>
</vm:MainViewModel.Items>
</vm:MainViewModel>
What am I doing wrong here, and how can I get the binding to work?
Upvotes: 2
Views: 4346
Reputation: 680
let's start with the View-model, we need to make data binding in this class:
class ViewModel
{
private ObservableCollection<string> _strings = new ObservableCollection<string>();
public ObservableCollection<string> Strings //It's our binding property
{
get
{
return _strings;
}
set
{
if (value==null)
{
throw new NullReferenceException();
}
_strings = value;
}
}
}
In this code we are using ObservableCollectin, which Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
Then we need to add some data:
public MainPage()
{
InitializeComponent();
ViewModel tempViewModel = new ViewModel();
var strings = new List<string> { "text1", "text2", "text3" };
tempViewModel.Strings = new ObservableCollection<string>(strings);
this.DataContext = tempViewModel;
}
And finaly we need to communicate our view-model with view:
<ListBox ItemsSource="{Binding Strings}"/>
Upvotes: 2