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;
}
Related
The second window in my WPF window is blank.
I've tried declaring the variable in multiple places, and assigning the value of new Send() separately from the declaration.
I've also made sure it isn't just my computer. I sent the compiled program to someone else and it did the same thing.
private void Button_Click(object sender, RoutedEventArgs e)
{
Send send = new Send();
send.Show();
}
The Send class:
public partial class Send : Window
{
public Send()
{
InitializeComponent();
ipIdBox.Text = GenerateIPID(GetIPAddress(), 8000);
}
private string GetIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
private string GenerateIPID(string ip, int port)
{
string[] ipseps = ip.Split('.'); // Split IP into parts
string code = ""; // Initialize the code
int counter = 0; // A counter (because every 4 digits are seperated)
foreach (string ippart in ipseps)
{
int ipparti = Convert.ToInt32(ippart);
string hippart = ipparti.ToString("X2");
code += hippart;
counter++;
if (counter == 1) {
counter = 0;
code += "-";
}
}
code += $"-{port.ToString("X4")}";
return code;
}
}
... and it's XAML
<Window x:Class="ScistMain.Send"
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:ScistMain"
mc:Ignorable="d"
Title="Send" Height="264.95" Width="451.774" OverridesDefaultStyle="True" Topmost="True">
<Grid>
<TextBlock x:Name="ipIdBox" Margin="0,124,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="34" TextAlignment="Center" FontSize="24" Text="7F00-0001-8000"/>
<TextBlock Margin="0,108,0,0" TextWrapping="Wrap" Text="Tell the person recieving to type this code:" VerticalAlignment="Top" Width="444" TextAlignment="Center"/>
<TextBlock Margin="0,10,0,0" TextWrapping="Wrap" Text="You are sending:" VerticalAlignment="Top" TextAlignment="Center" FontSize="18" FontWeight="Bold"/>
<Image x:Name="iconImg" Height="32" Margin="206,39,206,0" VerticalAlignment="Top" Width="32" Source="Resources/scist.ico"/>
<TextBlock Margin="0,76,0,0" TextWrapping="Wrap" Text="Placeholder Program" VerticalAlignment="Top" TextAlignment="Center"/>
<ProgressBar x:Name="pBar" HorizontalAlignment="Left" Height="34" Margin="10,124,0,0" VerticalAlignment="Top" Width="424" Visibility="Collapsed"/>
<Button Content="Cancel" HorizontalAlignment="Left" Margin="359,203,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>
I expect it to show the window I created in the designer:
but instead it shows a black window.
OverridesDefaultStyle="True" on the Window tag was the issue.
I had a similar question here: Input dialogue popup on mouse click
So when the user clicks on the canvas, a colored circle is marked where the mouse clicked, and a popup is displayed with two textboxes to get user input. I'm trying to accomplish two things: Instead of a popup, I would like to have a window displayed so the user can move the popup around (right now it's just a white space that sits in the same place). I also would like to add an 'ok' button so that when it's clicked, the two inputs get saved to their respective variables and the window closes.
I've tried adding a tag after the popup, but I get a xamlparseexception. I'm not sure what to do to make it so the popup is a window. Regarding the input text, I've seen many examples where the user enters text into a textbox and the data is saved to a variable, but nothing on saving it after the textbox window is closed. This is my first wpf application and I'm slowly trying to work through and learn it. Here's the code I have as it currently stands:
XAML:
<Window x:Class="CanvasStuff.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window" Height="410" Width="869">
<Grid Height="387">
<Label Content="Image" Height="32" HorizontalAlignment="Left" Margin="11,10,0,0"
Name="selectedFileName" VerticalAlignment="Top" Width="137"
Background="LightGray" BorderBrush="Gray" BorderThickness="1"/>
<Button Content="Browse File" Height="34" HorizontalAlignment="Left" Margin="154,6,0,0"
Name="BrowseButton" VerticalAlignment="Top" Width="119"
Foreground="Maroon" FontSize="16" FontFamily="Georgia" Click="BrowseButton_Click" />
<Button Content="Input Range and Heading" Height="34" HorizontalAlignment="Left" Margin="279,6,0,0"
Name="InputRangeBearing" VerticalAlignment="Top" Width="191"
Foreground="Maroon" FontSize="16" FontFamily="Georgia" Click="InputButton_Click" />
<Canvas Margin="0,45,2,8" x:Name="canvas1" MouseDown= "addNode_MouseDown">
<Popup Name="inputPopup" MouseDown="addNode_MouseDown" >
<Grid Height="150" Background="White" >
<Label Content="Range to object (m): " Height="28" HorizontalAlignment="Left" Margin="39,28,0,0" Name="label1" VerticalAlignment="Top" />
<TextBox x:Name="rangeToObject" Height="23" HorizontalAlignment="Left" Margin="151,30,0,0" VerticalAlignment="Top" Width="120" />
<Label Content="Heading to Object (0-360): " Height="28" HorizontalAlignment="Left" Margin="39,63,0,0" Name="label2" VerticalAlignment="Top" />
<TextBox x:Name="headingToObject" Height="23" HorizontalAlignment="Left" Margin="151,68,0,0" VerticalAlignment="Top" Width="120" />
</Grid>
</Popup>
</Canvas>
</Grid>
</Window>
Code behind:
namespace CanvasStuff
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = "c:\\";
dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedFileName = dlg.FileName;
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(selectedFileName));
canvas1.Background = brush;
BitmapImage bitmap = new BitmapImage();
}
}
private void InputButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Please click on known object to enter range and heading of that object.");
}
private void addNode_MouseDown(object sender, MouseButtonEventArgs e)
{
Point currentPoint = new Point();
if (e.ButtonState == MouseButtonState.Pressed)
currentPoint = e.GetPosition(this);
Ellipse ellipse = new Ellipse();
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 255, 255, 0);
ellipse.Fill = mySolidColorBrush;
ellipse.Width = 10;
ellipse.Height = 10;
Canvas.SetLeft(ellipse, e.GetPosition(canvas1).X);
Canvas.SetTop(ellipse, e.GetPosition(canvas1).Y);
canvas1.Children.Add(ellipse);
inputPopup.IsOpen = true;
}
}
}
To clarify, are you saying you'd prefer the popup box to appear as a completely separate window that the user can move around?
It's hard to know how deep to go, if this is your first WPF application. But it looks to me like you're straying into territory where MVVM and Databinding will be a great help to you.
I can strongly recommend that you spend some time getting to grips with the MVVM pattern, and WPF's databinding paradigm. There are plenty of good tutorials out there.
Once you've got the hang of the basics, I can highly recommend the MVVM-Light Toolkit to ease the pain of creating ViewModels and ICommands. It also contains a baisc messaging service, to simply communication between Windows and Views.
Sorry, I've not actually answered your question - but hopefully the links will give you some help :)
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.
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.
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.