XamlParseException when loading page - c#

I've found a weird problem in my app. When I open one of the pages, the app's InitializeComponent() method throws an XamlParseException. What can I do to get rid of this issue? I haven't found any obvious errors in my xaml code either. Here you can see my .cs and .xaml file of the page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
namespace app_name
{
public partial class newsummaryPage : PhoneApplicationPage
{
List<String> savingList;
List<String> projectList;
List<String> subjectsList;
IsolatedStorageSettings settings;
Boolean amISelectingProjects = true;
Boolean firstSelection = true;
String practicesummaryText;
public newsummaryPage()
{
InitializeComponent();
//Initialize settings
settings = IsolatedStorageSettings.ApplicationSettings;
}
private void nextButton_Click(object sender, RoutedEventArgs e)
{
//Load existing list into the savingList (For temporary storage)
savingList = null;
savingList = readSetting("practiceList") != null ? (List<String>)readSetting("practiceList") : new List<String>();
//Remove existing practiceList from IsolatedStorage
settings.Remove("practiceList");
//Add the new practice summary to the savingList
savingList.Add(practiceTextBox.Text.ToString());
//Save the savingList into practiceList in IsolatedStorage
settings.Add("practiceList", savingList);
//Save the summary text itself. Add "-practicesummary" to the end of the name to be able to add it without conflicts with the projectList and it's references
settings.Add(practiceTextBox.Text.ToString() + "-practicesummary", practicesummaryText);
//Save the settings
settings.Save();
MessageBox.Show("next");
}
private void newsummaryPage_Loaded(object sender, RoutedEventArgs e)
{
//Initialize the list
projectList = new List<String>();
try
{
//Load existing list
selectprojectsandsubjectsListBox.Items.Clear();
projectList.Clear();
MessageBox.Show("loaded");
projectList = readSetting("projectList") != null ? (List<String>)readSetting("projectList") : new List<String>();
selectprojectsandsubjectsListBox.ItemsSource = projectList;
}
catch (Exception)
{
//run method CurrentProjectNotEmpty();
}
}
private static object readSetting(string key)
{
return IsolatedStorageSettings.ApplicationSettings.Contains(key) ? IsolatedStorageSettings.ApplicationSettings[key] : null;
}
private void selectprojectsandsubjectsListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
}
private void selectprojectsandsubjectsListBox_Tap(object sender, System.Windows.SizeChangedEventArgs e)
{
//Select a project/subject depending on the amISelectingProjects variable
if (amISelectingProjects.Equals(true))
{
//The user is selecting a project. Get the name from the project and use it to get the subjects
var selectedItem = selectprojectsandsubjectsListBox.SelectedItem as String;
String item = selectedItem;
MessageBox.Show("select");
subjectsList = readSetting(item) != null ? (List<String>)readSetting(item) : new List<String>();
selectprojectsandsubjectsListBox = null;
selectprojectsandsubjectsListBox.ItemsSource = subjectsList;
//Set amISelectingProjects to false so that the user can select subjects next time
amISelectingProjects = false;
//Set the ListBox to multiple selection mode for selecting multiple subjects
selectprojectsandsubjectsListBox.SelectionMode = SelectionMode.Multiple;
//Tell the user what he should do next
MessageBox.Show("The subjects corresponding the the project you selected will now appear in the list. Tap on all the items you want to create a summary of and then press create when you're finished.");
}
else if (amISelectingProjects.Equals(false))
{
//The user is selecting a subject. Select multipe
if (firstSelection.Equals(true))
{
practicesummaryText = selectprojectsandsubjectsListBox.SelectedItem as String;
firstSelection = false;
}
else if (firstSelection.Equals(false))
{
//This is not the first subject that the user selects, therefore add some characters in between
practicesummaryText = practicesummaryText + ". New subject= " + selectprojectsandsubjectsListBox.SelectedItem as String;
}
}
}
}
}
My xaml file:
<phone:PhoneApplicationPage
x:Class="app_name.newsummaryPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="#FF03171B" Loaded="newsummaryPage_Loaded">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" MinHeight="1111"/>
<RowDefinition Height="0*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,0,0,0" Height="116" VerticalAlignment="Top">
<TextBlock Text="app name" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="New summary" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="newsummaryGrid" Margin="0,116,12,370">
<TextBox x:Name="practiceTextBox" HorizontalAlignment="Left" TextWrapping="Wrap" Width="458" Margin="0,27,0,0" Height="72" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="10,0,0,0" TextWrapping="Wrap" Text="Enter a new name for your summary:" VerticalAlignment="Top"/>
<Button x:Name="nextButton" Content="Create the summary" HorizontalAlignment="Left" Margin="0,553,0,0" VerticalAlignment="Top" Width="456" Click="nextButton_Click"/>
<ListBox x:Name="selectprojectsandsubjectsListBox" Margin="10,99,12,80" SelectionChanged="selectprojectsandsubjectsListBox_SelectionChanged" FontSize="36" Tap="selectprojectsandsubjectsListBox_Tap"/>
</Grid>
<!--ContentPanel - place additional content here-->
</Grid>
</phone:PhoneApplicationPage>
Inner exception:
$exception {System.Windows.Markup.XamlParseException: Failed to assign to property 'System.Windows.UIElement.Tap'. [Line: 32 Position: 172]
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at Knowledge_Organizer.newsummaryPage.InitializeComponent()
at Knowledge_Organizer.newsummaryPage..ctor()} System.Exception {System.Windows.Markup.XamlParseException}

See the output window, it usualy contains useful information about the exception's content.
or when the exception window appears, press break and go to visual studio DEBUG menu, choose windows->locals. the exception should appear in the locals view.
or try to debug and catch the exception, than see it's properties and inner message.

Related

How to embed video Files in WPF C# and change sources

I am working on an interactive app that shows different video's based on different stages, I am using C# and WPF and I am trying to use a MediaElement and change it source but it only let me play 1 video file and will not change to the next video, it will keep playing the same file over and over again, I just can't seem to understand why is this happening, I also couldn't find a solution to this online, I have embedded both video files "Stage8.mp4" and "Stage12.mp4" in my solution explorer, Both video files are set to copy if newer and content, also I don't think there is something wrong in the path because if I switch between them it will play the correct file, it just won't change the source in real time.
here are my codes:
C#:
using System;
using System.Windows;
namespace WPF_Tester
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
string NameChecker;
byte stage = 0;
private void BTN1_Click(object sender, RoutedEventArgs e)
{
NameChecker = "Name: " + TXT1.Text + " Last: " + TXT2.Text;
if (testlistview.Items.Contains(NameChecker))
{
MessageBox.Show("The name already exists.");
}
else
{
testlistview.Items.Add(NameChecker);
}
if (stage == 0)
{
TestElement.Source = new Uri("Stage12.mp4", UriKind.Relative);
TestElement.Play();
stage = 1;
}
if (stage == 1)
{
TestElement.Source = new Uri("Stage8.mp4", UriKind.Relative);
TestElement.Play();
stage = 0;
}
}
}
}
XAML:
<Window x:Class="WPF_Tester.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:WPF_Tester"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="Name:" FontSize="20" Margin="20,40,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"></TextBlock>
<TextBox x:Name="TXT1" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="18" Margin="80,40,0,0" MinWidth="30"></TextBox>
<TextBlock Text="Last Name:" Grid.Column="0" Grid.Row="0" FontSize="20" Margin="20,80,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"></TextBlock>
<TextBox x:Name="TXT2" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="18" Margin="120,80,0,0" MinWidth="30"></TextBox>
<Button x:Name="BTN1" HorizontalAlignment="Left" VerticalAlignment="Top" Content="Add Name" FontSize="20" Margin="20,180,0,0" Click="BTN1_Click"></Button>
<!-- here we set controls for the second column.-->
<ListView x:Name="testlistview" Grid.Column="1" Margin="20,40,20,20" FontSize="20" ></ListView>
<MediaElement Name="TestElement" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,200,20,0" UnloadedBehavior="Manual" Source="/Stage12.mp4" LoadedBehavior="Play"></MediaElement>
</Grid>
Thanks in advance and have a great day!
There is an else missing. Your second if statement always resets the file to the first. Adding else should implement the desired toggling.
if (stage == 0)
{
TestElement.Source = new Uri("Stage12.mp4", UriKind.Relative);
TestElement.Play();
stage = 1;
}
//we need an else here, otherwise source is always "Stage12.mp4
else if (stage == 1)
{
TestElement.Source = new Uri("Stage8.mp4", UriKind.Relative);
TestElement.Play();
stage = 0;
}

How can I change the content of a xaml page when a user clicks on a radio button? C# UWP

Hello Stack Overflow community,
I am developing a weather application using the Universal Windows Platform.
I am also using openweathermap to collect my weather data and Json.Net to parse the Json data that the api returns.
I have designed my app with a navigation pane using a split view control and a frame.
Inside of the frame I have placed a relative panel. In the xaml code I have provided you can see the content I would like to place inside of the frame when the user clicks on the radio button.
What I need to do is fill out the function named CurrentWeather_Checked, it's currently empty, but I am not sure what I need to put in there to get the behavior that I want.
1.MainPage.xaml
<Page
x:Class="Susanoo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Susanoo"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ThemesGeneric.xaml"/>
<ResourceDictionary Source="ThemesText.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
<SplitView x:Name="NavigationPane" DisplayMode="CompactInline">
<SplitView.Pane>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="44" />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button x:Name="HamburgerButton" Grid.Row="0" Style="{StaticResource MenuItemButtonStyle}" Tag="" Click="HamburgerButton_Click" />
<StackPanel x:Name="NavigationMenu" Orientation="Vertical" Grid.Row="1" Background="#FF42424C">
<RadioButton x:Name="Option1"
GroupName="Group1"
Style="{StaticResource NavigationButtonStyle}"
Tag=""
Checked="CurrentWeather_Checked"
Content="Current Weather"
/>
<RadioButton x:Name="Option2"
GroupName="Group1"
Style="{StaticResource NavigationButtonStyle}"
Tag=""
Checked="Option2Button_Checked"
Content="Favorite Cities"
/>
</StackPanel>
</Grid>
</SplitView.Pane>
<SplitView.Content>
<Frame x:Name="Content" Background="#FF31A877">
<Frame.ContentTransitions>
<TransitionCollection>
<NavigationThemeTransition>
<NavigationThemeTransition.DefaultNavigationTransitionInfo>
<EntranceNavigationTransitionInfo/>
</NavigationThemeTransition.DefaultNavigationTransitionInfo>
</NavigationThemeTransition>
</TransitionCollection>
</Frame.ContentTransitions>
<RelativePanel x:Name="contentDisplay">
<TextBlock x:Name="cityName" Style="{StaticResource displayText}" RelativePanel.AlignHorizontalCenterWithPanel="True" Text="City"/>
<TextBlock x:Name="countryName" Style="{StaticResource displayText}" RelativePanel.AlignHorizontalCenterWithPanel="True" RelativePanel.Below="cityName" Text="Country"/>
<TextBlock x:Name="currentTemp" Style="{StaticResource displayText}" RelativePanel.AlignHorizontalCenterWithPanel="True" RelativePanel.AlignVerticalCenterWithPanel="True" Text="Temp"/>
<TextBlock x:Name="minTemp" Style="{StaticResource smallDisplayText}" RelativePanel.LeftOf="countryName" RelativePanel.Below="currentTemp" Text="Min"/>
<TextBlock x:Name="maxTemp" Style="{StaticResource smallDisplayText}" RelativePanel.RightOf="countryName" RelativePanel.Below="currentTemp" Text="Max"/>
</RelativePanel>
</Frame>
</SplitView.Content>
</SplitView>
</Page>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace Susanoo
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
// Set the min size to 550 * 600
ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size { Width = 550, Height = 600 });
getCurrentWeather();
TitleBar();
}
async void getCurrentWeather()
{
WeatherObject currentWeather = new WeatherObject();
//units in Fahrenheit by default
currentWeather.Units = "Imperial";
//Searcy default for testing
currentWeather.RootObject.Name = "Searcy";
currentWeather.ZipCode = "72149";
await currentWeather.Task_getWeatherInfoByCityName();
//await currentWeather.Task_getWeatherInfoByZipCode();
if (currentWeather.RootObject != null)
{
cityName.Text = currentWeather.RootObject.Name;
countryName.Text = currentWeather.RootObject.Sys.Country;
currentTemp.Text = currentWeather.RootObject.Main.Temp.ToString();
if (currentWeather.Units == "Imperial")
{
currentTemp.Text = Math.Floor(currentWeather.RootObject.Main.Temp).ToString() + "° F";
minTemp.Text = "Low: " + Math.Floor(currentWeather.RootObject.Main.Temp_Min).ToString() + "°";
maxTemp.Text = "High: " + Math.Floor(currentWeather.RootObject.Main.Temp_Max).ToString() + "°";
}
else if (currentWeather.Units == "Metric")
{
currentTemp.Text = Math.Floor(currentWeather.RootObject.Main.Temp).ToString() + "° C";
minTemp.Text = "Low: " + Math.Floor(currentWeather.RootObject.Main.Temp_Min).ToString() + "°";
maxTemp.Text = "High: " + Math.Floor(currentWeather.RootObject.Main.Temp_Max).ToString() + "°";
}
//to use the images from openweathermap API
//not sure how to actually get it to show in the image in the main page?
string iconName = currentWeather.RootObject.Weather[0].Icon;
string imgUrl = "http://openweathermap.org/img/w/" + iconName + ".png";
//image.Source = imgUrl;
}
}
protected override void OnNavigatedTo(NavigationEventArgs args)
{
// Page was navigated to
var navManager = SystemNavigationManager.GetForCurrentView();
if (this.Frame.CanGoBack)
{
// Show Back button in title bar
navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
}
else
{
// Remove Back button from title bar
navManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
}
}
protected override void OnNavigatedFrom(NavigationEventArgs args)
{
// Page is being navigated away from
}
private void aboutButton_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(AboutPage));
}
private void TitleBar()
{
ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar;
titleBar.BackgroundColor = Colors.Black;
titleBar.ForegroundColor = Colors.White;
titleBar.ButtonBackgroundColor = Colors.Black;
titleBar.ButtonForegroundColor = Colors.White;
}
public Frame AppFrame { get { return Content; } }
private void CurrentWeather_Checked(object sender, RoutedEventArgs e)
{
// Here is where I am expecting I need to put the code
}
private void Option2Button_Checked(object sender, RoutedEventArgs e)
{
}
private void HamburgerButton_Click(object sender, RoutedEventArgs e)
{
NavigationPane.IsPaneOpen = !NavigationPane.IsPaneOpen;
}
}
}

WPF menu - Dynamic show and hide content

I need to create interactive menu. When option was choosen, I want to show appropriate content.
For example when option "Schemat bazy Northwind" was clicked, to my grid should be added Image. When another option was choosen previous content is removed and etc.
The only thing that comes to my mind is create functions which at the beginning clear grid and later add content(Is it possible?).
Please there anybody could direct me to solve this problem.
<Window x:Class="Northwind.AdminPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Panel administratora" WindowState="Maximized">
<StackPanel Name="bindingData">
<StatusBar>
<TextBlock FontSize="15" Text="{Binding ServerName}" Margin="0 0 30 0"></TextBlock>
<TextBlock FontSize="15" Text="{Binding ConnectionStatus}" Margin="0 0 30 0"></TextBlock>
<Label FontSize="15" Name="lblClock"></Label>
</StatusBar>
<DockPanel Height="55">
<Menu DockPanel.Dock="Top">
<MenuItem Header="Baza" Margin="10" FontSize="15"></MenuItem>
<MenuItem Header="Pomoc" Margin="10" FontSize="15">
<MenuItem x:Name="itemSchema" Header="Schemat bazy Northwind" Click="itmSchema_Click_1"></MenuItem>
</MenuItem>
</Menu>
</DockPanel>
<Grid x:Name="mainContent">
<!--add content -->
</Grid>
</StackPanel>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace Northwind
{
public partial class AdminPanel : Window
{
public string ServerName { get; set; }
public string ConnectionStatus { get; set; }
public AdminPanel(string name,string status)
{
InitializeComponent();
this.ServerName = name;
this.ConnectionStatus = status;
DispatcherTimer dtClockTime = new DispatcherTimer();
dtClockTime.Interval = new TimeSpan(0, 0, 1);
dtClockTime.Tick += dtClockTime_Tick;
dtClockTime.Start();
bindingData.DataContext = this;
}
private void dtClockTime_Tick(object sender, EventArgs e)
{
lblClock.Content = DateTime.Now.ToLongTimeString();
}
private void itmSchema_Click_1(object sender, RoutedEventArgs e)
{
//code
}
}
}
You can put the menu or whichever item you wanted to a conatainer (Grid) and you can use the Visibility attribute as collapsed when you want to hide that control.
if you are not using MVVM pattern then add it into the corresponding Event.
Container_Name.Visibility = Visibility.Collapsed;
Or else you can use the Xaml Triggers for obtain the same.
For that refer StackOverflow_Answer
Create a resources Dictionary and add this code
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- Set names two different ways -->
<Button Name="okButton">OK</Button>
<Button x:Name="cancelButton">Cancel</Button>
<ListBox>
<!-- Set content three different ways -->
<ListBoxItem Content="Item 1" />
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>
<ListBoxItem.Content>Item 3</ListBoxItem.Content>
</ListBoxItem>
</ListBox> </StackPanel>
when option "Schemat bazy Northwind" was clicked
private void SchematbazyNorthwind_Click(object sender, RoutedEventArgs e)
{
StackPanel stackPanel = null;
using (FileStream fs =
new FileStream("Dictionary1.xaml", FileMode.Open, FileAccess.Read))
{
stackPanel = (StackPanel)XamlReader.Load(fs);
}
MainGrid.Children.Add(stackPanel);
}
Load your Resources and attach to you grid

Telerik RadJumpList using DataVirtualizationMode.Automatic

I have a problem where im trying to use a Telerik Jump List with DataVirtualizationMode.Automatic, but i can't get it to work. The reason why i want to use this, is because i want my app to only download the data(games) which is in the current view of the Jump List control and not the whole data everytime. For example if i have searched for "Batman", and its returning 50 games, i don't want it to download and load all the games, only those i can see in the Jump List control.
Here is a sample of using DataVirtualizationMode.Automatic from Telerik, but i couldn't get it to work with my app: http://www.telerik.com/help/windows-phone/raddataboundlistbox-features-datavirtualization-automatic.html
Below is my Jump List control which i want to use with data virtualization.
MainPage.xaml:
<phone:PivotItem Header="Browse">
<Grid>
<telerikPrimitives:RadTextBox Name="txtSearch" HorizontalAlignment="Left" VerticalAlignment="Top" Height="80" Width="390"/>
<telerikPrimitives:RadImageButton Name="imgBtnSeachGame" VerticalAlignment="Top" HorizontalAlignment="Right" ButtonShape="Ellipse" BorderThickness="2" Margin="0,8,0,0" Click="imgBtnSeachGame_Click"></telerikPrimitives:RadImageButton>
<Controls:RadJumpList Name="jlGameList" ItemsSource="{Binding}" Tap="jlGameList_Tap" Margin="0,90,0,0" DataVirtualizationMode="Automatic">
<Controls:RadJumpList.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<Border Grid.Row="0" Background="{StaticResource PhoneAccentBrush}"
Padding="{StaticResource PhoneTouchTargetOverhang}"
Margin="0,0,0,0">
<TextBlock Name="tblGameTitle" Style="{StaticResource PhoneTextGroupHeaderStyle}" ManipulationStarted="tblGameTitle_ManipulationStarted" ManipulationCompleted="tblGameTitle_ManipulationCompleted">
<Run Text="{Binding GameTitle}"></Run>
</TextBlock>
</Border>
<Grid Background="#242424" Grid.Row="1">
<Image Name="imgGameList" Margin="0,0,0,0" Stretch="Fill" HorizontalAlignment="Left" VerticalAlignment="Top" Height="96" Width="96">
<Image.Source>
<BitmapImage UriSource="{Binding BoxArtFrontThumb}"
CreateOptions="BackgroundCreation" DecodePixelHeight="96" DecodePixelWidth="96" />
</Image.Source>
</Image>
<TextBlock Margin="110,0,0,0" Text="Platform" FontWeight="Bold" TextWrapping="Wrap" Foreground="YellowGreen" FontSize="{StaticResource PhoneFontSizeNormal}"/>
<TextBlock Name="txtPlatform" Margin="110,20,0,0" Text="{Binding Platform}"></TextBlock>
<TextBlock Text="Release Date" FontWeight="Bold" Margin="110,46,0,0" Foreground="YellowGreen" FontSize="{StaticResource PhoneFontSizeNormal}"/>
<TextBlock Name="txtReleaseDate" Margin="110,66,0,0" Text="{Binding ReleaseDate}"></TextBlock>
<!--</StackPanel>-->
</Grid>
<Grid Grid.Row="2"></Grid>
</Grid>
</DataTemplate>
</Controls:RadJumpList.ItemTemplate>
</Controls:RadJumpList>
</Grid>
</phone:PivotItem>
Below is where i bind my DataContext to my GetGamesListItems ObservableCollection in my GameData class. The imgBtnSearchGame_Click event method is being called when a user have typed for example "Batman" in my textbox txtSearch and tapped the button, it will then send the text to my GetGamesListData method.
MainPage.cs:
GameData gd = new GameData();
public MainPage()
{
InitializeComponent();
jlGameList.DataContext = gd.GetGamesListItems;
}
private void imgBtnSeachGame_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(txtSearch.Text))
{
gd.GetGamesListData(txtSearch.Text, "", "");
}
}
Below is where i download the data in XML for the game name searched for. For example if it is "Batman" it will find and return all games with "Batman". The "BoxArtFrontThumb" Property is where im storing all the images for each game and is using async, because sometimes there can be quite alot of images it has to download and show.
GameData.cs
public void GetGamesListData(string name, string platform, string genre)
{
var webClient = new WebClient();
webClient.DownloadStringCompleted += GetGamesListRequestCompleted;
webClient.DownloadStringAsync(new Uri("http://thegamesdb.net/api/GetGamesList.php?name=" + name));
}
private async void GetGamesListRequestCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
GetGamesListItems.Clear();
var feedXml = XDocument.Parse(e.Result);
var gameDataTasks = feedXml.Root.Descendants("Game").Select(
async x => new GetGamesList
{
ID = (int)x.Element("id"),
GameTitle = (string)x.Element("GameTitle"),
ReleaseDate = (string)x.Element("ReleaseDate") ?? "N/A",
Platform = (string)x.Element("Platform") ?? "N/A",
BoxArtFrontThumb = new Uri(await GetBoxArtFrontThumbAsync((int)x.Element("id")), UriKind.RelativeOrAbsolute),
}).ToList();
var gameData = await Task.WhenAll(gameDataTasks);
foreach (var item in gameData)
{
GetGamesListItems.Add(item);
}
}
}
Below is where its finding and storing the images for the games.
public async Task<string> GetBoxArtFrontThumbAsync(int id)
{
var client = new HttpClient();
var result = await client.GetStringAsync("http://thegamesdb.net/api/GetArt.php?id=" + id);
var feedXml = XDocument.Parse(result);
var gameData = feedXml.Root.Descendants("Images").Select(x => new GetArt
{
BoxArtFrontThumb = new Uri(GetBoxArtFrontThumb(x), UriKind.RelativeOrAbsolute),
}).ToList();
return gameData.Single().BoxArtFrontThumb.ToString();
}
private static string GetBoxArtFrontThumb(XElement gameNode)
{
string data = "http://thegamesdb.net/banners/" + (string)gameNode.Descendants("boxart")
.FirstOrDefault(b => (string)b.Attribute("side") == "front");
if (data == "http://thegamesdb.net/banners/")
{
data = "/NoImage.jpg";
}
return data;
}
I really hope i explained this well enough and hope that there is someone that can help me solve this problem. Thanks.
Although you are using JumpList, the mechanism for Virtualizing the data is the same as the DataBoundListBox. (You can find more information here in the DataBoundListBox docs. There is a good tutorial using an OData service.)
In order for the Automatic mode to work properly, you need to be using Telerik's VirtualizingDataCollection object and initialize it with the proper arguments (count and page size).
I don't see this in the code you have provided above, can you please open a support ticket so that I can investigate further? See my comment above for the link. Let me know the ticket number and I'll provide further assistance.

'System.Windows.Controls.Grid' does not contain a definition for 'setRow' WP 8 project

I am trying to make a cryptogram puzzle for Windows 8 Phone.
.net framework is 4.5
I am encountering this following error: 'System.Windows.Controls.Grid' does not contain a definition for 'setRow' at Grid.setRow(txt, x); I want to create textboxes dynamically, without using XAML...
To the best of my knowledge, Windows.Controls.Grid has a static method Grid.setRow(UIelement, int)..
Here is MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Resources;
using System.IO;
namespace CryptogramPuzzle
{
public partial class MainPage : PhoneApplicationPage
{
List<string> quotes;
List<TextBox> tb;
int length = 0;
int width;
int height;
// Constructor
public MainPage()
{
InitializeComponent();
Random r = new Random();
string encodedStr;
InitializeComponent();
getQuotes();
int rInt = r.Next(0, quotes.Count()); //generates random index for a quote selection
encodedStr = Encryption.encode(quotes[rInt]);
length = encodedStr.Length;
createTxtBox(0, 0);
}
/// <summary>
/// Loads quotes from the text file
/// </summary>
public void getQuotes()
{
quotes = new List<string>();
try
{
StreamResourceInfo sInfo = Application.GetResourceStream(new Uri("/CryptogramPuzzle;component/Resources/Puzzles.txt", UriKind.Relative));
StreamReader sr = new StreamReader(sInfo.Stream);//feeds the reader with the stream
string line;
while ((line = sr.ReadLine()) != null)
{
quotes.Add(line);
}
sr.Close();
// System.Console.WriteLine(quotes[0]);
}
catch (Exception e)
{
throw (e);
}
}
public void createTxtBox(int x, int y)
{
TextBox txt = new TextBox();
RowDefinition newRow = new RowDefinition();
newRow.Height = new GridLength(0, GridUnitType.Auto);
ContentPanel.RowDefinitions.Add(newRow);
txt.MinHeight = 10;
txt.MinHeight = 10;
ContentPanel.Children.Add(txt);
Grid.setRow(txt, x);
}
}
}
Here is my MainPage.xaml:
<phone:PhoneApplicationPage
x:Class="CryptogramPuzzle.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- LOCALIZATION NOTE:
To localize the displayed strings copy their values to appropriately named
keys in the app's neutral language resource file (AppResources.resx) then
replace the hard-coded text value between the attributes' quotation marks
with the binding clause whose path points to that string name.
For example:
Text="{Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}"
This binding points to the template's string resource named "ApplicationTitle".
Adding supported languages in the Project Properties tab will create a
new resx file per language that can carry the translated values of your
UI strings. The binding in these examples will cause the value of the
attributes to be drawn from the .resx file that matches the
CurrentUICulture of the app at run time.
-->
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
</Grid>
<!--Uncomment to see an alignment grid to help ensure your controls are
aligned on common boundaries. The image has a top margin of -32px to
account for the System Tray. Set this to 0 (or remove the margin altogether)
if the System Tray is hidden.
Before shipping remove this XAML and the image itself.-->
<!--<Image Source="/Assets/AlignmentGrid.png" VerticalAlignment="Top" Height="800" Width="480" Margin="0,-32,0,0" Grid.Row="0" Grid.RowSpan="2" IsHitTestVisible="False" />-->
</Grid>
Please help me to fix this error, getting pretty desperate!
Thank you.
If it's a standard framework method, I'm pretty sure standard Pascal-casing rules (the guidelines that MS follows at least) dictate it would be called SetRow and not setRow.
And indeed it is.

Categories