Binding JSON JArray to Listview in UWP Issue - c#

In visual studio universal windows app, I am trying to bind a JArray to a Listview. It seems to compile fine and the quantity of rows populate into the Listview but no data fills the rows. What am I doing wrong here or is this even possible?
using Newtonsoft.Json.Linq;
XAML
<ListView Grid.Row="0" x:Name="lstJobData">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="8">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Path=job_id}" FontSize="14" Foreground="White"/>
<TextBlock Grid.Row="1" Text="{Binding Path=job_number}" FontSize="14" Foreground="White"/>
<TextBlock Grid.Row="2" Text="{Binding Path=ship_type}" FontSize="14" Foreground="White"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
JArray from Service layer (converted to Jarray from Json string)
{[
{ "job_id": 399783, "job_number": "XYZ-J111111", "ship_type": "c" },
{ "job_id": 445672, "job_number": "XYZ-J222222", "ship_type": "p" },
{ "job_id": 896543, "job_number": "XYZ-J333333", "ship_type": "f" }
]}
XAML (Code behind)
private async void Button1_Click(object sender, RoutedEventArgs e)
{
MyServices.Service1Client client = new MyServices.Service1Client();
var itemSource = await client.GetDTAsync();
JArray result = JArray.Parse(itemSource);
lstJobData.ItemsSource = result;
}

When we set the JArray to the ItemsSource property of the ListView, we can not use the path in the XAML. The path means Property-path, it will point to the property of the item. Also there is no job_id property in the item.
If you want to use path in XAML, we should be able to create a Job class. And in the Job, we should be able to define the job_id, job_number and
ship_type properties.
Then we should be able to add the Job to the ObservableCollection of the Job class.
For example:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button HorizontalAlignment="Right" VerticalAlignment="Top" Click="Button1_Click" >click</Button>
<ListView VerticalAlignment="Bottom" HorizontalAlignment="Center" Grid.Row="0" x:Name="lstJobData">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="8">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Path=job_id}" FontSize="14" Foreground="Red" />
<TextBlock Grid.Row="1" Text="{Binding Path=job_number}" FontSize="14" Foreground="Red" />
<TextBlock Grid.Row="2" Text="{Binding Path=ship_type}" FontSize="14" Foreground="Red" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
The code behind:
public sealed partial class MainPage : Page
{
private ObservableCollection<Job> Jobs;
public MainPage()
{
this.InitializeComponent();
Jobs = new ObservableCollection<Job>();
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
string newJson = #"
[
{'job_id':399783,'job_number':'XYZ-J111111','ship_type':'c'},
{'job_id':445672,'job_number':'XYZ-J222222','ship_type':'p'},
{'job_id':896543,'job_number':'XYZ-J333333','ship_type':'f'}
]";
JArray result = JArray.Parse(newJson);
for (int i = 0; i < result.Count; i++)
{
Jobs.Add(new Job() { job_id = (string)result[i]["job_id"], job_number = (string)result[i]["job_number"], ship_type = (string)result[i]["ship_type"] });
}
lstJobData.ItemsSource = Jobs;
}
}
internal class Job
{
public string job_id { get; set; }
public string job_number { get; set; }
public string ship_type { get; set; }
}

Related

Cannot change the VirtualizationMode attached property on an ItemsControl after Measure is called on the ItemsHost panel

When i try to set VirtualizationMode on my ListView to Recycling I get the error from the title:
Cannot change the VirtualizationMode attached property on an
ItemsControl after Measure is called on the ItemsHost panel.
I am trying to set the attached property programmatically but when I try to define the VirtualizationMode in XAML designer throws the same error from the title. Anyone had similar problems like this?
My view in XAML is:
<Window x:Class="FinalVirtualizationApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FinalVirtualizationApp"
mc:Ignorable="d"
Title="MainWindow" Height="900" Width="800"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
TextElement.Foreground="{DynamicResource MaterialDesignBody}"
TextElement.FontWeight="Regular"
TextElement.FontSize="13"
TextOptions.TextFormattingMode="Ideal"
TextOptions.TextRenderingMode="Auto"
Background="{DynamicResource MaterialDesignPaper}"
FontFamily="{DynamicResource MaterialDesignFont}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<GroupBox Grid.Row="0" Header="UI virtualization options">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox Content="UI virtualization" VerticalAlignment="Center" IsChecked="{Binding IsUIVirtualization}"/>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Content="Container Recycling:" VerticalAlignment="Center"/>
<ComboBox Grid.Column="1" VerticalAlignment="Center" SelectedValue="{Binding ContainerRecyclingType}" SelectedValuePath="Content">
<ComboBoxItem>Recycling</ComboBoxItem>
<ComboBoxItem>Standard</ComboBoxItem>
</ComboBox>
</Grid>
<CheckBox Content="Deferred scrolling" Grid.Row="1" VerticalAlignment="Center" IsChecked="{Binding IsDeferredScrolling}">
</CheckBox>
<Grid Grid.Row="1" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="74*"/>
<ColumnDefinition Width="253*"/>
</Grid.ColumnDefinitions>
<Label Content="Scroll unit" VerticalAlignment="Center" Margin="0,0,0,1"/>
<ComboBox Grid.Column="1" VerticalAlignment="Center" SelectedValue="{Binding ScrollUnitType}" SelectedValuePath="Content" Grid.ColumnSpan="2" Margin="0,2,0,3">
<ComboBoxItem>Item</ComboBoxItem>
<ComboBoxItem>Pixel</ComboBoxItem>
</ComboBox>
</Grid>
</Grid>
</GroupBox>
<GroupBox Grid.Row="1" Header="Data virtualization">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<GroupBox Header="ItemsProvider">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<Label Content="Number of Items: "/>
<TextBox Width="60" Text="{Binding NumberOfItems}"/>
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Label Content="Fetch delay(ms): "/>
<TextBox Width="60" Text="{Binding FetchDelay}"/>
</StackPanel>
</Grid>
</GroupBox>
<GroupBox Grid.Row="1" Header="Collection">
<StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,2,0,0">
<TextBlock Text="Type:" Margin="5" TextAlignment="Right" VerticalAlignment="Center"/>
<RadioButton x:Name="rbNormal" GroupName="rbGroup" Margin="5" Content="List(T)" VerticalAlignment="Center" Command="{Binding CollectionTypeChangeCommand}" CommandParameter="List"/>
<RadioButton x:Name="rbVirtualizing" GroupName="rbGroup" Margin="5" Content="VirtualizingList(T)" VerticalAlignment="Center" Command="{Binding CollectionTypeChangeCommand}" CommandParameter="VirtualizingList"/>
<RadioButton x:Name="rbAsync" GroupName="rbGroup" Margin="5" Content="AsyncVirtualizingList(T)" VerticalAlignment="Center" Command="{Binding CollectionTypeChangeCommand}" CommandParameter="AsyncVirtualizingList"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,2,0,0">
<TextBlock Text="Page size:" Margin="5" TextAlignment="Right" VerticalAlignment="Center"/>
<TextBox x:Name="tbPageSize" Margin="5" Text="{Binding PageSize}" Width="60" VerticalAlignment="Center"/>
<TextBlock Text="Page timeout (s):" Margin="5" TextAlignment="Right" VerticalAlignment="Center"/>
<TextBox x:Name="tbPageTimeout" Margin="5" Text="{Binding PageTimeout}" Width="60" VerticalAlignment="Center"/>
</StackPanel>
</StackPanel>
</GroupBox>
</Grid>
</GroupBox>
<StackPanel Orientation="Horizontal" Grid.Row="2">
<TextBlock Text="Memory Usage:" Margin="5" VerticalAlignment="Center"/>
<TextBlock x:Name="tbMemory" Margin="5" Width="80" Text="{Binding MemoryUsage}" VerticalAlignment="Center"/>
<Button Content="Refresh" Margin="5" Width="100" VerticalAlignment="Center" Command="{Binding RefreshCommand}"/>
</StackPanel>
<ListView Grid.Row="3" Name="lvItems">
<ListView.ItemTemplate>
<DataTemplate>
<Expander Header="{Binding DeviceName}">
<StackPanel>
</StackPanel>
</Expander>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
And i try to set the VirtualizationMode here:
public void SetUIVirtualizationOptions()
{
listView.SetValue(VirtualizingStackPanel.IsVirtualizingProperty, IsUIVirtualization);
listView.SetValue(ScrollViewer.IsDeferredScrollingEnabledProperty, IsDeferredScrolling);
if(ContainerRecyclingType == "Recycling")
listView.SetValue(VirtualizingStackPanel.VirtualizationModeProperty, VirtualizationMode.Recycling);
else
listView.SetValue(VirtualizingStackPanel.VirtualizationModeProperty, VirtualizationMode.Standard);
if (ScrollUnitType == "Item")
listView.SetValue(VirtualizingPanel.ScrollUnitProperty, ScrollUnit.Item);
else
listView.SetValue(VirtualizingPanel.ScrollUnitProperty, ScrollUnit.Pixel);
}
Edit: My Window code behind where i pass the listview to viewmodel is:
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel(lvItems);
}
}
And the viewmodel part of the code (minus getters and setters for less space taken):
public class MainWindowViewModel : BindableBase
{
#region private fields
private ListView listView;
private bool isUIVirtualization;
private bool isDeferredScrolling;
private string containerRecyclingType;
private string scrollUnitType;
private int numberOfItems;
private int fetchDelay;
private string collectionType;
private int pageSize;
private int pageTimeout;
private string memoryUsage;
private DemoItemProvider itemsProvider;
#endregion
#region commands
public RelayCommand<string> CollectionTypeChangeCommand { get; set; }
public RelayCommand RefreshCommand { get; set; }
public RelayCommand<string> ContainerRecyclingTypeChangeCommand { get; set; }
public RelayCommand<string> ScrollUnitTypeChangeCommand { get; set; }
#endregion
public MainWindowViewModel(ListView lvItems)
{
this.listView = lvItems;
PageSize = 100;
PageTimeout = 30;
NumberOfItems = 1000000;
FetchDelay = 1000;
CollectionTypeChangeCommand = new RelayCommand<string>(CollectionTypeChangeFunc);
RefreshCommand = new RelayCommand(RefreshFunc);
ContainerRecyclingTypeChangeCommand = new RelayCommand<string>(ContainerRecyclingTypeChangeFunc);
ScrollUnitTypeChangeCommand = new RelayCommand<string>(ScrollUnitTypeChangeFunc);
// use a timer to periodically update the memory usage
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick += timer_Tick;
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
MemoryUsage = string.Format("{0:0.00} MB", GC.GetTotalMemory(true) / 1024.0 / 1024.0);
}
#region command methods
public void CollectionTypeChangeFunc(string type)
{
CollectionType = type;
}
public void RefreshFunc()
{
SetUIVirtualizationOptions();
itemsProvider = new DemoItemProvider(NumberOfItems, FetchDelay);
if (collectionType == "List")
{
listView.ItemsSource = new List<DataItem>(itemsProvider.FetchRange(0, itemsProvider.FetchCount()));
}
else if (collectionType == "VirtualizingList")
{
listView.ItemsSource = new VirtualizingCollection<DataItem>(itemsProvider, pageSize);
}
else if (collectionType == "AsyncVirtualizingList")
{
listView.ItemsSource = new AsyncVirtualizingCollection<DataItem>(itemsProvider, pageSize, pageTimeout * 1000);
}
}
public void ContainerRecyclingTypeChangeFunc(string type)
{
ContainerRecyclingType = type;
}
public void ScrollUnitTypeChangeFunc(string type)
{
ScrollUnitType = type;
}
public void SetUIVirtualizationOptions()
{
listView.SetValue(VirtualizingStackPanel.IsVirtualizingProperty, IsUIVirtualization);
listView.SetValue(ScrollViewer.IsDeferredScrollingEnabledProperty, IsDeferredScrolling);
if(ContainerRecyclingType == "Recycling")
listView.SetValue(VirtualizingStackPanel.VirtualizationModeProperty, VirtualizationMode.Recycling);
else
listView.SetValue(VirtualizingStackPanel.VirtualizationModeProperty, VirtualizationMode.Standard);
if (ScrollUnitType == "Item")
listView.SetValue(VirtualizingPanel.ScrollUnitProperty, ScrollUnit.Item);
else
listView.SetValue(VirtualizingPanel.ScrollUnitProperty, ScrollUnit.Pixel);
}
#endregion
}
The code source for VirtualizingStackPanel indicates that this property can only be set before initialization of the panel:
/// <summary>
/// Attached property for use on the ItemsControl that is the host for the items being
/// presented by this panel. Use this property to modify the virtualization mode.
///
/// Note that this property can only be set before the panel has been initialized
/// </summary>
public static readonly DependencyProperty VirtualizationModeProperty =
DependencyProperty.RegisterAttached("VirtualizationMode", typeof(VirtualizationMode), typeof(VirtualizingStackPanel),
new FrameworkPropertyMetadata(VirtualizationMode.Standard));
You can indeed check this behavior later in the file:
//
// Set up info on first measure
//
if (HasMeasured)
{
VirtualizationMode oldVirtualizationMode = InRecyclingMode ? VirtualizationMode.Recycling : VirtualizationMode.Standard;
if (oldVirtualizationMode != virtualizationMode)
{
throw new InvalidOperationException(SR.Get(SRID.CantSwitchVirtualizationModePostMeasure));
}
}
else
{
HasMeasured = true;
}
and there is no way (according to source code) to set this HasMeasured property back to False unless you destroy and recreate the ListView.
It is so as the message says:
Your not allowed to _change the VirtualizationMode attached property
on an ItemsControl after Measure is called on the ItemsHost panel.
This means, that if ListView is already shown virtualizing mechanism being used and you are not allowed to change it.
If you set Visibility of ListView in XAML to Collapsed and set it only later to the Visible, then you can set the VirtualizationMode in code behind to wished value, but only once(so you can't change it after ListView become visible)!
private void Button_Click(object sender, RoutedEventArgs e)
{
listView.SetValue(VirtualizingStackPanel.VirtualizationModeProperty, VirtualizationMode.Recycling);
listView.Visibility = Visibility.Visible;
}
XAML:
<ListView x:Name="listView" ... Visibility="Collapsed">

Binding a list of object to grid

Trying to render a ListView with a grid into it. The grid contains two columns. The first one, with a button. The second one, with a Label.
Model contains two attributes. First one, a List of specific object. Second one, a string.
Finally, the label of the grid inside of listview will be binded to the one random attribute of list of object of the Model.
My best approach is:
<ListView x:Name="intervectionList"
ItemsSource="{Binding .}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="5">
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="1"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Text="Play" Grid.Row="0" Grid.Column="0" Clicked="OnLogginClicked"/>
<Label Grid.Row="0" Grid.Column="1" Text="{Binding random_attribute}"/>
<BoxView Color="Navy" HeightRequest="1" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
CODE-BEHIND:
public Intervection()
{
InitializeComponent();
var obj= new Model();
this.BindingContext = prueba.List_of_object;
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaiseOnPropertyChange([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public ViewModel()
{
_viewmodel = new ViewModel();
}
private ViewModel _viewmodel;
private string _attribute1;
public string Attribute1
{
get { return _attribute1; }
set { _attribute1= value; RaiseOnPropertyChange(); }
}
.............
}
public class Model
{
public List<obj> Intervencion;
public string attribute2;
// Helpers...
}
That is not rendering anything.
I tried successive approaches. Coming from Basic ListView with string, ListView of object,... and so on. The problem is coming from when I insert the grid.
After check Stackoverflow. I found this link Create Grid from Code-Behind, but this is not serving to my purpose because I can´t re-write the view model. (I, even, tried to coded it).
As usual, thanks mates.
I have added the VerticalOptions to the Listview and Grid.
I have created a viewmodel in which I have one property, the list of items.
The viewmodel also implements INotifyPropertyChanged.
You can read about INotifyPropertyChanged here.
The INotifyPropertyChanged interface is used to notify clients,
typically binding clients, that a property value has changed.
XAML :
<ListView ItemsSource="{Binding MyObservableCollection}" VerticalOptions="FillAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Padding="5" VerticalOptions="Fill">
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="1"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Text="Play" Grid.Row="0" Grid.Column="0"/>
<Label Grid.Row="0" Grid.Column="1" Text="{Binding .}"/>
<BoxView Color="Navy" HeightRequest="1" Grid.Row="1"
Grid.Column="0" Grid.ColumnSpan="2"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ViewModel :
public class ListViewWithGridViewModel : INotifyPropertyChanged
{
private ObservableCollection<string> _myObservableCollection;
public ListViewWithGridViewModel()
{
MyObservableCollection = new ObservableCollection<string>(new List<string> { "abc", "xyz", "pqr", "aaa", "abc", "xyz", "pqr", "aaa", "abc", "xyz", "pqr", "aaa" });
}
public ObservableCollection<string> MyObservableCollection
{
get { return _myObservableCollection; }
set
{
_myObservableCollection = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
XAML.cs :
public partial class ListViewWithGrid : ContentPage
{
public ListViewWithGrid()
{
InitializeComponent();
BindingContext = new ListViewWithGridViewModel();
}
}
Finally I got it. The xaml needed for it is the next one (you can complet all code coming from the code´s question). Posted just in case you all want to use another approach. Proper answer (more elegant) is #Rohit´s answer.
<ContentPage.Resources>
<ResourceDictionary>
<Color x:FactoryMethod="FromHex" x:Key="fondoBlancoPalido">
<x:Arguments>
<x:String>#F2F2F2</x:String>
</x:Arguments>
</Color>
</ResourceDictionary>
</ContentPage.Resources>
<ListView x:Name="listView" ItemsSource="{Binding .}" BackgroundColor="{StaticResource fondoBlancoPalido}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid Padding="5">
<Grid.RowDefinitions>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition Height="10"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
<ColumnDefinition Width="3*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Grid.Column="0" Clicked="OnStartClicked" Image="play.png" BackgroundColor="Transparent" HorizontalOptions="Center" Grid.RowSpan="2"/>
<Label Grid.Row="0" Grid.Column="1" Text="Hora de Inicio: " XAlign="Center" YAlign="Center" TextColor="Black" FontAttributes="Bold"/>
<Label Grid.Row="0" Grid.Column="2" Text="{ Binding attribute3 }" XAlign="Center" YAlign="Center" TextColor="Black"/>
<Label Grid.Row="1" Grid.Column="1" Text="Encargado de la Tarea: " XAlign="Center" YAlign="Center" TextColor="Black" FontAttributes="Bold"/>
<Label Grid.Row="1" Grid.Column="2" Text="{ Binding attribute4 }" XAlign="Center" YAlign="Center" TextColor="Black"/>
<BoxView Color="Navy" HeightRequest="2" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3"/>
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Listview not displaying data but showing namespace plus datamodel

I am using the folloowing class but its not allowing me to display show_times in my xaml its just comming up
popcornpk.datamodel.fetchtiming
public class FetchTiming
{
public string id { get; set; }
public string theater_name { get; set; }
public string address { get; set; }
public List<string> show_times { get; set; }
public string screen_id { get; set; }
public string title { get; set; }
}
public class MovieDetail
{
public MovieDetails movie_details { get; set; }
public List<FetchTiming> fetch_timing { get; set; }
}
My Class call
public async Task<MovieDetail> GetMovieShowtimesAsync()
{
string jsonresult = await WCFRESTServiceCall("GET", "movie_details");
var jarray = JsonConvert.DeserializeObject<MovieDetail>(jsonresult);
return jarray;
}
This is my xamlmethod call I hav eno idea what is going on the data is being returned ok but I just cant seem to dispaly it
private async void listViewShowtimes_Loaded(object sender, RoutedEventArgs e)
{
popcornpk_Dal _dal = new popcornpk_Dal();
MovieDetail _showTimes = await _dal.GetMovieShowtimesAsync();
var listView = (ListView)sender;
listView.ItemsSource = _showTimes.fetch_timing.ToList();
}
Xaml Of DataTemplate
<PivotItem x:Name="pvtShowTimes" Header="showtimes">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListView x:Name="listViewShowtimes" ItemsSource="{Binding}" Loaded="listViewShowtimes_Loaded">
<DataTemplate>
<StackPanel Height="505">
<TextBlock FontSize="13" x:Name="txtshowtime" Text="{Binding theater_name}" HorizontalAlignment="Left" Margin="19,223,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="212" Foreground="White" Height="29" SelectionChanged="txtTtile_SelectionChanged"/>
<TextBlock FontSize="13" x:Name="txtshow_times" Text="{Binding address}" HorizontalAlignment="Left" Margin="19,223,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="212" Foreground="White" Height="29" SelectionChanged="txtTtile_SelectionChanged"/>
</StackPanel>
</DataTemplate>
</ListView>
</Grid>
</PivotItem>
Below is a screen shot of the app running on the device any help be greatly apreciated.
Ok So i have it at least displaying the thertre name which is good on the show times screen but its still not allowing me to display the show_times field.
<ListView x:Name="listViewShowtimes" ItemsSource="{Binding}" Loaded="listViewShowtimes_Loaded">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock FontSize="13" Grid.Row="0" Grid.Column="0" x:Name="txtshowtime" Text="{Binding theater_name}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="212" Foreground="White" Height="29" />
<TextBlock FontSize="13" Grid.Row="1" Grid.Column="0" x:Name="txtshow_times" Text="{Binding show_times}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="212" Foreground="White" Height="29" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
I think what i need to no is how to bind a list of strings through xaml Problem I have i need the show times to appear below the cinema name you see their
You have Text="{Binding show_times}" so In your class FetchTiming,
public List<string> show_times { get; set; }
is a list so if you bind it to a TextBlock, it will simply do ToString(). You have to add inside the template another ListView like:
<TextBlock FontSize="13" Grid.Row="0" Grid.Column="0" x:Name="txtshowtime" Text="{Binding theater_name}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Width="212" Foreground="White" Height="29" />
<ListView ItemsSource={Binding show_times} />
And will do the trick.

Access DataTemplate Control At Run Time

I am Working on Windows phone 8.1.I Making Simple ListView Demo Which is Contain two Image And Two TextBlock.
<ListView x:Name="lst1" Grid.ColumnSpan="2" >
<ListView.ItemTemplate>
<DataTemplate >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image x:Name="imgSender" Source="Assets/button_register.png" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="8,15,8,8" />
<TextBlock Text="{Binding Sender}" FontSize="18" Foreground="Black" FontWeight="Bold" HorizontalAlignment="Center" Margin="0,12,0,0"/>
<Image x:Name="imgReceiver" Source="Assets/button_register.png" Grid.Row="1" Stretch="None" VerticalAlignment="Top" Margin="4,0" />
<TextBlock Text="{Binding Receiver}" FontSize="18" Foreground="Black" FontWeight="Bold" HorizontalAlignment="Center" Grid.Row="1" VerticalAlignment="Top"/>
<Image Source="Assets/scroll_line_addcategory.png" Grid.Row="2" Stretch="None" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="4,8,4,0" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And My Problem is That I Want to Set the Visibility of 'imgSender' at Runtime in Xaml.cs File.
Is Anybuddy Have Any Idea For Access UI Control Contain by Data Template.
<ListView x:Name="lst1" Grid.ColumnSpan="2" >
<ListView.ItemTemplate>
<DataTemplate >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image Visibility="{Binding SenderVisibility}" x:Name="imgSender" Source="Assets/button_register.png" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="8,15,8,8" />
<TextBlock Text="{Binding Sender}" FontSize="18" Foreground="Black" FontWeight="Bold" HorizontalAlignment="Center" Margin="0,12,0,0"/>
<Image x:Name="imgReceiver" Source="Assets/button_register.png" Grid.Row="1" Stretch="None" VerticalAlignment="Top" Margin="4,0" />
<TextBlock Text="{Binding Receiver}" FontSize="18" Foreground="Black" FontWeight="Bold" HorizontalAlignment="Center" Grid.Row="1" VerticalAlignment="Top"/>
<Image Source="Assets/scroll_line_addcategory.png" Grid.Row="2" Stretch="None" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="4,8,4,0" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And my Model Class is
public class User : INotifyPropertyChanged
{
private string sender = string.Empty;
private string receiver = string.Empty;
private string senderVisibility = string.Empty;
private string receiverVisibility = string.Empty;
public string Sender
{
get
{
return sender;
}
set
{
if (value != this.sender)
{
this.sender = value;
NotifyPropertyChanged("Sender");
}
}
}
public string Receiver
{
get
{
return this.receiver;
}
set
{
if (value != this.receiver)
{
this.receiver = value;
NotifyPropertyChanged("Receiver");
}
}
}
public string ReceiverVisibility
{
get
{
return this.receiverVisibility;
}
set
{
if (value != this.receiverVisibility)
{
this.receiverVisibility = value;
NotifyPropertyChanged("ReceiverVisibility");
}
}
}
public string SenderVisibility
{
get
{
return this.senderVisibility;
}
set
{
if (value != this.senderVisibility)
{
this.senderVisibility = value;
NotifyPropertyChanged("SenderVisibility");
}
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
If your ListView contains only one item you can easily subscribe to Loaded event of imgSender and then control it's Visibility.
private Image _imgSender;
void Image_Loaded(object sender, RoutedEventArgs e)
{
_imgSender = sender as Image();
}
void AnotherMethod()
{
if (_imgSender != null)
_imgSender.Visibility = Visibility.Collapsed;
}
EDIT
FOR MULTIPLE ITEMS
void HideImage(int elementIndex)
{
var container = lst1.ContainerFromIndex(elementIndex) as ListViewItem;
var imageSender = (container.Content as Grid).Children[0] as Image;
imageSender.Visibility = Visibility.Collapsed;
}
You can add a BooleanToVisibilityConverter
<Page.Resources>
<converter:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Page.Resources>
<ListView x:Name="lst1" Grid.ColumnSpan="2"
ItemsSource="{Binding TelecomCollection}">
<ListView.ItemTemplate>
<DataTemplate >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image x:Name="imgSender" Source="Assets/button_register.png" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="8,15,8,8"
Visibility="{Binding ShowImgReceiver, Converter={StaticResource BooleanToVisibilityConverter}}"/>
<TextBlock Text="{Binding Sender}" FontSize="18" Foreground="Black" FontWeight="Bold" HorizontalAlignment="Center" Margin="0,12,0,0"/>
<Image x:Name="imgReceiver" Source="Assets/button_register.png" Grid.Row="1" Stretch="None" VerticalAlignment="Top" Margin="4,0" />
<TextBlock Text="{Binding Receiver}" FontSize="18" Foreground="Black" FontWeight="Bold" HorizontalAlignment="Center" Grid.Row="1" VerticalAlignment="Top"/>
<Image Source="Assets/scroll_line_addcategory.png" Grid.Row="2" Stretch="None" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="4,8,4,0" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Then in your item class you can add ShowImgReceiver
public class Telecom
{
string Receiver {get; set;}
string Sender {get; set;}
bool ShowImgReceiver{get; set;}
}
In your binding class
public class ViewModel
{
public ObservableCollection<Telecom> TelecomCollection {get; set;}
}
If you want to make an item's image visibility Collapsed, then
TelecomCollection[0].ShowImgReceiver = false;
and to make it again Visible
TelecomCollection[0].ShowImgReceiver = true;

Windows 8 Live Hub Tile

I am using Callisto Toolkit to create a live hub tile in a Windows 8 application but I am not managing to perform data binding for my live tile. The code I am using is the following:
<callisto:LiveTile x:Name="liveTile2"
Background="#3B5998"
ItemsSource="{Binding Tile}"
Grid.Column="5"
Grid.Row="1"
Height="250"
VerticalAlignment="Top"
BorderBrush="White" BorderThickness="1"
Margin="5"
Direction="Up">
<callisto:LiveTile.ItemTemplate>
<DataTemplate>
<Grid Margin="5">
<Grid.DataContext>
<ViewModel:Tile/>
</Grid.DataContext>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image x:Name="tileImage" Source="{Binding Image}"/>
<TextBlock Foreground="White"
TextWrapping="Wrap"
TextTrimming="WordEllipsis"
FontSize="14"
Grid.Row="1" Margin="0,71,0,0" Text="{Binding Msg}" />
</Grid>
</DataTemplate>
</callisto:LiveTile.ItemTemplate>
<callisto:LiveTile.DataContext>
<ViewModel:LiveTileData/>
</callisto:LiveTile.DataContext>
</callisto:LiveTile>
And this is the class for the tile:
namespace Test.ViewModel
{
public class Tile
{
public string Msg { get; set; }
public Uri Image { get; set; }
}
public class LiveTileData
{
private static ObservableCollection<Tile> tileData = new ObservableCollection<Tile>();
public static ObservableCollection<Tile> TileData
{
get
{
return tileData;
}
}
}
}
You are doing binding incorrectly. You should do binding LiveTile's ItemsSource as ObservableCollection<Tile> TileData. Moreover the DataContext is passed to the LiveTile itself not to its template. Check out the below code.
XAML
<callisto:LiveTile x:Name="liveTile2"
Background="#3B5998"
ItemsSource="{Binding TileData}"
Grid.Column="5"
Grid.Row="1"
Height="250"
VerticalAlignment="Top"
BorderBrush="White" BorderThickness="1"
Margin="5"
Direction="Up">
<callisto:LiveTile.ItemTemplate>
<DataTemplate>
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image x:Name="tileImage" Source="{Binding Image}" Stretch="None"/>
<TextBlock Foreground="White"
TextWrapping="Wrap"
TextTrimming="WordEllipsis"
FontSize="14"
Grid.Row="1" Margin="0,71,0,0" Text="{Binding Msg}" />
</Grid>
</DataTemplate>
</callisto:LiveTile.ItemTemplate>
<callisto:LiveTile.DataContext>
<ViewModel:LiveTileData />
</callisto:LiveTile.DataContext>
</callisto:LiveTile>
C#
public class Tile
{
public string Msg { get; set; }
public Uri Image { get; set; }
}
public class LiveTileData
{
public LiveTileData()
{
tileData.Add(new Tile { Msg = "Stack Overflow", Image = new Uri("http://jenswinter.com/image.axd?picture=stackoverflow-logo-250.png") });
tileData.Add(new Tile { Msg = "Super User", Image = new Uri("http://superuser.com/content/superuser/img/logo.png") });
}
private static ObservableCollection<Tile> tileData = new ObservableCollection<Tile>();
public static ObservableCollection<Tile> TileData
{
get
{
return tileData;
}
}
}

Categories

Resources