XamlParseException in windows Phone Application - c#

I am trying to create my first Windows phone application but I keep getting this "XamlParseException" thrown at me.It looks like the error is coming from the InitializeComponent() method which is a shock because it was automatically created by VS.
Here is the Exception :
XamlParseException
Failed to assign to property 'System.Windows.FrameworkElement.Loaded'. [Line: 14 Position: 39]
Here is the code behind :
namespace WinHomeWork1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, TextChangedEventArgs e)
{
myTextBox.Focus();
}
private void ClickMe_Click(object sender, RoutedEventArgs e)
{
if (myTextBox.Text.CompareTo("1 2 3 4") == 0)
{
myTextBlock.Text = "You have won!";
}
else
myTextBlock.Text = "You have Lost";
}
}
}
Here is the Xaml Code :
<phone:PhoneApplicationPage
x:Class="WinHomeWork1.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" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">
<!--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>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Brahman Initiative" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="108 mintes" 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">
<TextBox Height="72" HorizontalAlignment="Left" Margin="0,6,0,0" Name="myTextBox" Text="" VerticalAlignment="Top" Width="460" />
<Button Content="Go" Height="74" HorizontalAlignment="Left" Margin="234,88,0,0" Name="ClickMe" VerticalAlignment="Top" Width="222" Click="ClickMe_Click" />
<TextBlock Height="68" HorizontalAlignment="Left" Margin="12,88,0,0" Name="myTextBlock" Text="" VerticalAlignment="Top" Width="200" />
</Grid>
</Grid>
<!--Sample code showing usage of ApplicationBar-->
<!--<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="MenuItem 1"/>
<shell:ApplicationBarMenuItem Text="MenuItem 2"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->
</phone:PhoneApplicationPage>
The program has only 3 elements, 1) A TextBox 2) A TextBlock and a 3) Button. The user inputs data into the textBox then clicks a "Go" button, if the input is "1 2 3 4" the app will display "You have Won" in the textBlock, if any other input has been entered it will display " You have lost".Please Help, I do not know any Xaml so I can't play around with the Xaml code.

Change the parameter e in your PhoneApplicationPage_Loaded to an instance of the RoutedEventArgs class:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
myTextBox.Focus();
}

Your error is due to PhoneApplicationPage_Loaded event handler method. It should be like this:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
myTextBox.Focus();
}

Related

UWP Navigation Pane go back button not working

I'm learning UWP and trying to implement GO BACK button in a navigation pane. I put go-back button under a RelativePanel right below menu button. The below is my current XAML page:
<Page
x:Class="LearningUWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:LearningUWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Windows.UI.Xaml.Controls"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<RelativePanel>
<Button Name="Menu" FontFamily="Segoe MDL2 Assets" Content="" FontSize="36" Click="Menu_Click"></Button>
<Button RelativePanel.Below="Menu" Style="{StaticResource NavigationBackButtonNormalStyle}" Name="Back" FontSize="36" Click="Back_Click"></Button>
</RelativePanel>
<SplitView Name="MySplitView"
Grid.Row="1"
DisplayMode="CompactOverlay"
OpenPaneLength="200"
CompactPaneLength="56"
HorizontalAlignment="Left">
<SplitView.Pane>
<ListBox SelectionMode="Single"
Name="IconsListBox"
SelectionChanged="IconsListBox_SelectionChanged"
>
<ListBoxItem Name="ShareListBoxItem">
<StackPanel Orientation="Horizontal" >
<TextBlock FontFamily="Segoe MDL2 Assets" FontSize="36" Text=""/>
<TextBlock Text="Share" FontSize="24" Margin="20, 0, 0, 0"/>
</StackPanel>
</ListBoxItem>
<ListBoxItem Name="FavoritesListBoxItem" >
<StackPanel Orientation="Horizontal" >
<TextBlock FontFamily="Segoe MDL2 Assets" FontSize="36" Text=""/>
<TextBlock Text="Favorites" FontSize="24" Margin="20, 0, 0, 0"/>
</StackPanel>
</ListBoxItem>
</ListBox>
</SplitView.Pane>
<SplitView.Content>
<TextBlock Margin="50, 0, 0, 0" Name="ResultTextBlock"/>
</SplitView.Content>
</SplitView>
</Grid>
</Page>
And the XAML's code-behind:
namespace LearningUWP
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Menu_Click(object sender, RoutedEventArgs e)
{
MySplitView.IsPaneOpen = !MySplitView.IsPaneOpen;
}
private void IconsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ShareListBoxItem.IsSelected)
ResultTextBlock.Text = "shared";
else if (FavoritesListBoxItem.IsSelected)
ResultTextBlock.Text = "Favorites";
}
private void Back_Click(object sender, RoutedEventArgs e)
{
if (this.Frame.CanGoBack)
this.Frame.GoBack();
}}}
For some reason, after I click the Go back button, it doesn't work as expected, and what is more, I find this.Frame.CanGoBack = false.
How to solve it?
From the code that you have posted we can see that this.Frame is actually the refering to the root frame of the application, which at the moment has only navigated to a single page (MainPage) (As defined in your App.xaml.cs). Thus there is no page that it can go back to (this.Frame.CanGoBack = false).
A little in depth explanation :
If you go into App.xaml.cs file in your project, in the OnLaunched() method you will find the following code :
rootFrame.Navigate(typeof(MainPage), e.Arguments);
Here the application, after launch will navigate the rootFrame to the MainPage.
When you use this.Frame from your MainPage it actually refers to the rootFrame, which at this moment has only navigated to the MainPage, thus it does not have any page that it can go back to , hence this.Frame.CanGoBack = false.
Solution :
When you use a SplitView, in the content you should specify a Frame which you can use to navigate between different pages . Thus your app will look something like this :
Here Red rectangle is used to show the rootFrame where as Blue is used to show the Frame which you have to define in your SplitView content.
For this, you need to make minor modifications to your code something like this :
XAML
<Page
.....
.....
<SplitView Name="MySplitView"
.....>
<SplitView.Pane>
.....
</SplitView.Pane>
<SplitView.Content>
<Frame x:Name="appFrame"></Frame>
</SplitView.Content>
</SplitView>
</Page>
C#
private void IconsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ShareListBoxItem.IsSelected)
appFrame.Navigate(typeof(page1));//navigating to page1
else if (FavoritesListBoxItem.IsSelected)
appFrame.Navigate(typeof(page2));//navigating to page2
}
private void Back_Click(object sender, RoutedEventArgs e)
{
if (appFrame.CanGoBack)
appFrame.GoBack();
}
Hope this helps..!

Going from Page to Window with Timer on Gives a STA Problem?

I have a problem where I run my program and it gives me a STA Error on my "Test" Window. It does not have an error if I don't have a timer going from the Page I am running till the window. I'll show and Example:
public Page1()
{
InitializeComponent();
Task.Delay(2000).ContinueWith(_ =>
{
var page = new TestW();
page.Show();
}
);
}
This is from my Page1 to open up my TestW ( Test Window )
My main code looks like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Luk_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void Button_Click(object sender, RoutedEventArgs e) // Login
{
Main.Content = new Page1();
Framep.Visibility = Visibility.Visible;
GridS.Visibility = Visibility.Hidden;
}
}
And my XAML Code:
<Window x:Class="date_app.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:date_app"
mc:Ignorable="d"
Title="MainWindow" Height="700" Width="400"
ResizeMode="NoResize"
WindowStyle="None"
WindowStartupLocation="CenterScreen"
AllowsTransparency="True"
Background="Transparent"
>
<Border BorderBrush="Black"
BorderThickness="1.5"
CornerRadius="10"
>
<Border.Background>
<ImageBrush x:Name="ImageBrush" ImageSource="Images\bgapp.png" Stretch="None"/>
</Border.Background>
<Grid>
<StackPanel x:Name="Framep">
<Frame x:Name="Main" />
</StackPanel>
<StackPanel x:Name="GridS">
<!--X Luk Knappen.-->
<Grid>
<Button BorderBrush="Transparent" Name="Luk" Margin="360, 10, 10, 0" Background="Transparent" Click="Luk_Click">
<Button.Content>
<Image Source="Images\Ikke-navngivet.png" Height="20" Width="35" IsHitTestVisible="False" />
</Button.Content>
</Button>
</Grid>
<Grid>
<Image Source="Images\DateL.png" Height="200"/>
</Grid>
<!--Username.-->
<Grid>
<TextBox Style="{StaticResource WatermarkTextbox}" Name="Email" Height="30" Width="300" FontSize="20" FontFamily="Comic Sans MS" Text="Hello" Margin="0 40 0 0" TextChanged="Email_TextChanged"/>
</Grid>
<!--Password.-->
<Grid>
<TextBox Style="{StaticResource WatermarkTextbox1}" Name="Pass" Height="30" Width="300" FontSize="20" FontFamily="Comic Sans MS" Text="Hello" Margin="0 35 0 0" TextChanged="Pass_TextChanged"/>
</Grid>
<!--Login Knap.-->
<Grid>
<Button Grid.Column="0" Content="Log ind" Width="80" Height="30" FontSize="20" Margin="0 100 0 0" Click="Button_Click" />
</Grid>
<!--Opret Bruger-->
<Grid>
<Button Grid.Column="0" Content="Opret Bruger" Width="140" Height="30" FontSize="20" Margin="0 20 0 0" />
</Grid>
</StackPanel>
</Grid>
</Border>
Page1 Code:
<Page x:Class="date_app.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:gif="https://github.com/XamlAnimatedGif/XamlAnimatedGif"
xmlns:local="clr-namespace:date_app"
mc:Ignorable="d"
d:DesignHeight="700" d:DesignWidth="400"
Title="LoadingM">
<Border BorderBrush="Black"
BorderThickness="1.5"
CornerRadius="10"
>
<Border.Background>
<ImageBrush x:Name="ImageBrush" ImageSource="Images\bgapp.png" Stretch="None"/>
</Border.Background>
<Grid>
<TextBlock Text="LOADING. . ." FontSize="50" FontFamily="Comic Sans MS"/>
<Image gif:AnimationBehavior.SourceUri="Images\CatGif.gif" />
</Grid>
</Border>
The problem I have: If I run with the Task Delay My test Window gets an STA Error that I don't know how to fix.
If I run without the Task Delay It just opens it all up but no STA Error.
I am trying to do this:
When I press on the Login button It is supposed to open the Page1 and hide the main window for a " Loading " Screen and then after the delay to close Main window + Page1 down to Open up the New Window. Been sitting with this for a little while :) Thanks in advance!
-- Test Window Is plain. No code there.
This is the Background.
The problem is that the Action given to ContinueWith will not be exectued on the UiThread but on a free ThreadPool-Thread, so the new TestW object will be constructed and used by a non STA-Thread. But any WPF-UI-component must be constructed and used by an STA-Thread.
The solution is to replace your Task.Delay() with
Task.Delay(2000).ContinueWith(_ =>
{
Dispatcher.Invoke(() =>
{
var page = new TestW();
page.Show();
});
});
This will delegate your execution back to the UiThread.

WPF minimizing window into bottom of parrent window

I try to make a "email messenger". I have two windows. Main window, there is ribbon with bookmarks and one button (New message). This button invoke second window NewMessage. The Mainwindow is owner of the NewMessage window.
MainWindow:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
NewMessage newmessage = new NewMessage();
newmessage.Show();
}
}
}
MainWindow XAML:
<Window x:Class="Messenger.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:Messenger"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="New Message" Height="20" Width="80
" HorizontalAlignment="Left" Margin="35,46,0,0" VerticalAlignment="Top" Click="Button_Click" />
<TabControl HorizontalAlignment="Left" Height="254" Margin="34,44,0,0" VerticalAlignment="Top" Width="461" Background="{x:Null}" SelectedIndex="1">
<TabItem Header="Delivered" Visibility="Hidden" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Delivered" Visibility="Visible" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Sent" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Trash" Width="80">
<Grid Background="#FFE5E5E5"/>
</TabItem>
</TabControl>
</Grid>
NewMessage:
public partial class NewMessage : Window
{
public NewMessage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
NewMessage XAML:
<Window x:Class="Messenger.NewMessage"
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:Messenger"
mc:Ignorable="d"
Title="NewMessage" Height="351.047" Width="814.398">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4*"/>
<ColumnDefinition Width="27*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="23*"/>
<RowDefinition Height="24*"/>
<RowDefinition Height="243*"/>
<RowDefinition Height="31*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="Komu" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBox Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Top" />
<Label Grid.Row="1" Content="Předmět" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Top" />
<RichTextBox HorizontalAlignment="Left" Height="243" Grid.Row="2" VerticalAlignment="Top" Width="806" Grid.ColumnSpan="2">
<FlowDocument>
<Paragraph>
<Run Text="Sem zadejte text zprávy"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
<Button Grid.Row="3" Content="Odeslat" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" Width="75" Margin="0,5,90,0"/>
<Button Grid.Row="3" Content="Storno" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" Width="75" Margin="0,5,10,0" Click="Button_Click"/>
</Grid>
I would like to, when I minimize NewMessage window, this window minimize to the bottom of MainWindow "taskbar". If you know gmail, there is the same principle. Any idea?

Exception when databinding result from contact query in wp8 c#

I have been attempting to embed a contact picker within my windows phone 8 app. The idea is simple...show contacts, allow the user to tap the contacts they wish to save for use by my app, save selected items. Implementing this has not been as simple as i thought though.
I have the following code, mainly from MSDN samples:
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 Microsoft.Phone.UserData;
using System.Diagnostics;
namespace appNamespace
{
public partial class contact : PhoneApplicationPage
{
public contact()
{
InitializeComponent();
}
private void showContacts(object sender, RoutedEventArgs e)
{
Contacts cons = new Contacts();
//Identify the method that runs after the asynchronous search completes.
cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);
//Start the asynchronous search.
cons.SearchAsync(String.Empty, FilterKind.None, "Contacts Test #1");
}
void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
//Do something with the results.
MessageBox.Show(e.Results.Count().ToString());
try
{
//Bind the results to the user interface.
ContactResultsData.DataContext = e.Results;
}
catch (System.Exception)
{
//No results
}
if (ContactResultsData.Items.Any())
{
ContactResultsLabel.Text = "results";
}
else
{
ContactResultsLabel.Text = "no results";
}
}
public void saveContacts(object sender, RoutedEventArgs e)
{
String strItem;
foreach (Object selecteditem in ContactResultsData.SelectedItems)
{
MessageBox.Show(selecteditem.ToString());
strItem = selecteditem as String;
ContactResultsLabel.Text = strItem;
System.Diagnostics.Debug.WriteLine(strItem);
MessageBox.Show("Saving " + strItem);
}
}
}
}
When running the code on a device, Lumia 920, the app shows the count of how many contacts, but does not show the databound list. (See XAML below) Instead, the app halts and an exception is thrown (ApplicationException, no details offered b debugger)
<phone:PhoneApplicationPage
x:Class="appNamespace.contact"
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="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="appName" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="contacts" 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">
<StackPanel Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,10" >
<TextBlock Name="ContactResultsLabel" Text="results are loading..." Style="{StaticResource PhoneTextLargeStyle}" TextWrapping="Wrap" />
<ListBox Name="ContactResultsData" ItemsSource="{Binding}" Height="436" Margin="12,0" SelectionMode="Multiple" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Name="ContactResults" Style="{StaticResource PhoneFontSizeMedium}" Text="{Binding Path=DisplayName, Mode=OneWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
<Button x:Name="showButton" Content="Show Contacts" HorizontalAlignment="Left" VerticalAlignment="Top" Width="218" Height="90" Margin="0,531,0,0" Click="showContacts"/>
<Button x:Name="saveButton" Content="Save Contacts" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="238,531,0,0" Width="218" Height="90"/>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
Really hope someone can help, I cannot figure out why this exception arises. Thank you.
<TextBlock Name="ContactResults" Style="{StaticResource PhoneFontSizeMedium}" Text="{Binding Path=DisplayName, Mode=OneWay}" />
PhoneFontSizeMedium is, as the name indicates, a size. You can't apply it directly to a TextBlock.
What you're trying to do is:
<TextBlock Name="ContactResults" FontSize="{StaticResource PhoneFontSizeMedium}" Text="{Binding Path=DisplayName, Mode=OneWay}" />

SelectionChanged Event for ListBox. Pass parameters between pages

I am building a WP7 app that consist on one listbox in the first page to show the id of several task and a detail page to show the details for each task (selected).
I need to pass the task id from the first page to the second one. I know that it is carried out by SelectionChanged event of the listbox.
This is my XAML code:
<phone:PhoneApplicationPage
x:Class="TaskListAlpha03.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" d:DesignWidth="480" d:DesignHeight="696"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True"
xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls">
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="TaskListListBoxTemplate">
<StackPanel Orientation="Vertical" Margin="0,0,0,20">
<TextBlock Text="{Binding Crm_object_id}" FontSize="32" FontFamily="Segoe WP Bold" Foreground="Gray"/>
<!--<TextBlock Text="{Binding Comment}" Margin="10,0,0,0"/> -->
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<!--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>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,40">
<TextBlock x:Name="ApplicationTitle" Text="TASK LIST ALPHA" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="tasks" 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">
<ListBox
x:Name="allTaskListTasksListBox"
ItemsSource="{Binding AllTaskListTasks}"
ItemTemplate="{StaticResource TaskListListBoxTemplate}"
SelectionChanged="allTaskListTasksListBox_SelectionChanged" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>
And this is the cs code:
private void allTaskListTasksListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
NavigationService.Navigate(new Uri("/View/Details.xaml?msg=" + lbi.Content.ToString(), UriKind.RelativeOrAbsolute));
}
In the second page I have this sample code to check if it works:
protected override void OnNavigatedTo
(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string msg = "";
if (NavigationContext.QueryString.TryGetValue("msg", out msg))
PageTitle.Text = msg;
}
When I execute the application I have a "NullReferenceException".
Sorry for my english :S and thanks.
A couple of points here...
1) I would use a Tap event on the item rather than a selection changed event. It helps prevent accidental navigation.
2) If you do use the selectionchanged event, try the following code to get your item. Your current code will attempt to fire if an items is de-selected in the list.
private void allTaskListTasksListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(e.AddedItems.Count > 0) // the items that were added to the "selected" collection
{
var mySelectedItem = e.AddedItems[0] as myItemType;
if(null != mySelectedItem) // prevents errors if casting fails
{
NavigationService.Navigate(
new Uri("/View/Details.xaml?msg=" + mySelectedItem.Crm_object_id,
UriKind.RelativeOrAbsolute)
);
}
}
}
The problem is with ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);. You are casting it to ListBoxItem which in fact it is your custom item you bind it to the ListBox. Do something like:
var item = ((sender as ListBox).SelectedItem as YourItem);

Categories