Reputation: 67
I'm new to the whole data binding thing with XAML for WP8.1. I've been searching on the internet and I can't seem to find a straight-forward answer to my problem.
I have a ListBox control on my page with 3 columns. What I need to do is fill each column with it's respective data.
I have a class that defines a "CompleteStation" which is made up of 3 strings (StationName, Distance, and GasPrice)
This is the XAML code for the ListBox... How am I able to pass the ListBox a CompleteStation (3 strings) and have it separate each string into the correct column?
This is my XAML code below. In my main class, I'm just adding a CommpleteStation item to the ListBox.
Also, do I need to reference the CompleteStation class in the XAML code? If yes, how do I do this?
<ListBox Name="listBoxStations" FontSize="20" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="480" Background="#e6e6e6" Margin="0,10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Station}"/>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Distance}"/>
<TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding Price}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Thanks!
-Johan
Upvotes: 0
Views: 1129
Reputation: 222572
Lets say your CompleteStation is an ObservableCollection
which implements NotifyPropertyChanged
, Then XAML should be as follows
<ListBox Name="listBoxStations" ItemSource={Binding CompleteStation} FontSize="20" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="480" Background="#e6e6e6" Margin="0,10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Station}"/>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Distance}"/>
<TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding Price}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Your Model:
public sealed class CommpleteStation
{
public string Station{get;set;}
public string Distance{get;set;}
public string Price{get;set;}
}
Your ViewModel:
public sealed class MyViewModel
{
public ObservableCollection<CommpleteStation> CommpleteStations{get;private set;}
public MyViewModel()
{
CommpleteStations = new ObservableCollection<CommpleteStation>();
CommpleteStations.Add(new CommpleteStation{Station="One", Distance="15",Price="130"};
}
}
Then,
IN codebehind for your UI, the "View", you instantiate your ViewModel and set it as the DataContext for your View.
public MyView()
{
this.DataContext = new MyViewModel();
}
Upvotes: 1