Binding Collection To ListView Control In UWP

2015-12-04 13:58:37来源:作者:C-Sharpcorner人点击

<

="" div="">

<Grid><TextBlockText="{BindingBrand}"></TextBlock><TextBlockText="{BindingModel}"></TextBlock><TextBlockText="{BindingColor}"></TextBlock></Grid>

You could have any number of properties of model and controls and bind them the way you want.

Till now what we have done? We added a ListView to display list of items and then added DataTemplate to it. <DataTemplate> can contain only one item so we added a Grid container and added code to it. Inside Grid we defined three text blocks for our three properties of Car class. Bind it to properties of our Model (Car). Make sure name after Binding is the same as property of class to which you want to bind that TextBlock.

MainPage.xaml will look like the following,

Step 6:Now we should have some data list to show. Expand MainPage.xaml and double click MainPage.xaml.cs file. Add the following code. (Add using System.Collections.ObjectModel; namespace as well to use ObersvableCollection Class. You could use List<T> as well but ObservableCollection notify the ListView when values of its objects are changed).

ObservableCollection<Car>dataList=newObservableCollection<Car>();Carc1=newCar(){Brand="Ferrari",Model="Lamborghinis",Color="Red"};Carc2=newCar(){Brand="Honda",Model="GLI",Color="Black"};Carc3=newCar(){Brand="Porsche",Model="968snowplow",Color="White"};dataList.Add(c1);dataList.Add(c2);dataList.Add(c3);MyList.ItemsSource=dataList;

Note:I am using temporary data objects for 3 cars here but these could be any objects got from database or other data sources. It will look like:

Run the project by clicking local machine (windows 10) and you will see overlapped text, why? Because inside Grid we just declared three TextBlocks. We didn't set their layout, now just enclose them with <StackPanel> like the following,

<StackPanel><TextBlockText="{BindingBrand}"></TextBlock><TextBlockText="{BindingModel}"></TextBlock><TextBlockText="{BindingColor}"></TextBlock></StackPanel>

Now run again to see the following,

相关文章

    无相关信息

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台