how to remove XamlParseException in windows phone 8? - c#

When I run my app in windows phone 8 emulator, I am getting this Exception thrown after which I can't run my app.
MainPage.xaml
<phone:PhoneApplicationPage
x:Class="LightBrowser.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="PortraitOrLandscape" 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>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="Light Browser" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button x:Name="Go" Content="Go" HorizontalAlignment="Right" Margin="0,27,0,0" VerticalAlignment="Top" Click="Button_Click_1" Width="79"/>
<phone:WebBrowser x:Name="Light_Browser" Margin="0,99,0,0"/>
<Button x:Name="Back" Content="Back" HorizontalAlignment="Right" Margin="343,-24,0,0" VerticalAlignment="Top" Height="65" Click="Back_Click"/>
<Button x:Name="Refresh" Content="Refresh" Margin="170,-24,159,0" VerticalAlignment="Top" Height="65" Click="Back_Click" HorizontalAlignment="Center"/>
<TextBox x:Name="URL" Margin="0,27,68,0" VerticalAlignment="Top" Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" TextOptions.TextHintingMode="Animated" AcceptsReturn="True" Text="http://www.google.co.in/"/>
<Button x:Name="Home" Content="Home" HorizontalAlignment="Left" Margin="3,-23,0,0" VerticalAlignment="Top" Click="Home_Click" Height="67" Width="110"/>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
MainPage.xaml.cs
namespace LightBrowser
{
public partial class MainPage : PhoneApplicationPage
{
private Stack<Uri> _history = new Stack<Uri>();
private string home = "http://www.google.co.in/";
private Uri _current = null;
// Constructor
public MainPage()
{
InitializeComponent();
Light_Browser.Navigate(new Uri("http://www.google.co.in/", UriKind.Absolute));
Light_Browser.IsScriptEnabled = true;
}
private void Button_Click_1(object sender, NavigatingEventArgs e)
{
Uri url = e.Uri;
URL.Text = url.ToString();
string site = URL.Text;
Light_Browser.Navigate(new Uri(site, UriKind.Absolute));
}
private void Home_Click(object sender, NavigatingEventArgs e)
{
Light_Browser.Navigate(new Uri(home, UriKind.Absolute));
Uri url = e.Uri;
URL.Text = url.ToString();
}
private void Back_Click(object sender, NavigatingEventArgs e)
{
Light_Browser.GoBack();
Uri url = e.Uri;
URL.Text = url.ToString();
}
private void Refresh_Click(object sender, NavigatingEventArgs e)
{
Uri url = e.Uri;
URL.Text = url.ToString();
string site=URL.Text;
Light_Browser.Navigate(new Uri(site, UriKind.RelativeOrAbsolute));
}
private void Browser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
{
MessageBox.Show("Navigation to this page failed, check your internet connection");
}
private async void Browser_Navigated(object sender, NavigationEventArgs e)
{
// If we navigated back, pop the last entry
if (_history.Count > 0 && _history.Peek() == e.Uri)
{
_history.Pop();
}
// Otherwise, if this isn't the first navigation, push the current
else if (_current != null)
{
_history.Push(_current);
}
// The current page is now the one we've navigated to
_current = e.Uri;
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) {
base.OnBackKeyPress(e);
if (_history.Count == 0)
{
// No history, allow the back button
// Or do whatever you need to do, like navigate the application page
return;
}
// Otherwise, if this isn't the first navigation, push the current
else
Light_Browser.GoBack();
}
}
}
XamlParseException Occured
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in System.Windows.ni.dll
And this error points to InitializeComponent();

Related

detect multitouch while pressed c#

I want to detect a touch event and do something while my finger is touching down.
What is the event I need?
I tried Manipulation*, Pointer*, Touch*, Stylus*, Holding*, etc...
If you have a sample code, better.
The most accurate code I have is this. But only works with finger moving.
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Rectangle Name="Rect1" IsManipulationEnabled="True" Fill="Blue" HorizontalAlignment="Center" Height="100" VerticalAlignment="Center" Width="100" Margin="108,50,309,169" ManipulationDelta="Rect1_ManipulationDelta" />
<Rectangle Name="Rect2" IsManipulationEnabled="True" Fill="Blue" HorizontalAlignment="Center" Height="100" VerticalAlignment="Center" Width="100" Margin="338,50,79,169" ManipulationDelta="Rect2_ManipulationDelta" />
<TextBox Name="Text1" Text="0" HorizontalAlignment="Left" Height="23" Margin="108,267,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="100"/>
<TextBox Name="Text2" Text="0" HorizontalAlignment="Left" Height="23" Margin="338,267,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="100"/>
</Grid>
namespace WpfApplication2
{
public partial class MainWindow : System.Windows.Window
{
System.Windows.Input.ManipulationModes currentMode = System.Windows.Input.ManipulationModes.All;
public MainWindow()
{
InitializeComponent();
}
private void Rect1_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
int variable = 0;
variable = Convert.ToInt32(Text1.Text);
variable++;
Text1.Text = variable.ToString();
}
private void Rect1_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
int variable = 0;
variable = Convert.ToInt32(Text1.Text);
variable++;
Text1.Text = variable.ToString();
}
private void Rect2_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
int variable = 0;
variable = Convert.ToInt32(Text2.Text);
variable++;
Text2.Text = variable.ToString();
}
private void Rect2_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
int variable = 0;
variable = Convert.ToInt32(Text2.Text);
variable++;
Text2.Text = variable.ToString();
}
}
}
Touch* events will give you just touch. Pointer* will give you touch and mouse and stylus.
Use *Down to know when a touch goes down and *Up to know when it goes up. If you want to do something repeatedly while the touch is down, create a DispatcherTimer on the *Down and stop it on the *Up
UIElement/ContentElement.TouchDown is the event you need to accomplish what you are after.
Example:
<Rectangle Name="Rect1" IsManipulationEnabled="True" Fill="Blue" HorizontalAlignment="Center" Height="100" VerticalAlignment="Center" Width="100" Margin="108,50,309,169" TouchDown="Rect1_TouchDown" />
private void Rect1_TouchDown(object sender, TouchEventArgs e)
{
// Do stuff
}
For further information, refer to:
http://msdn.microsoft.com/en-us/library/system.windows.uielement.touchdown(v=vs.110).aspx and
http://msdn.microsoft.com/en-us/library/ms754010(v=vs.110).aspx

Errors when editting existing WP8 project

So I am just starting out with this stuff and have run into some strife. There was a pivot soundboard application that I needed to change into a series of panorama pages but have the same functionality.
I have finished all the xaml and c# appropriately but I think because I had to create a new MainPage and delete the older one I have created several errors. I suspect they all have a similar cause so I will just provide three.
Error 1 The type 'SoundBoard.MainPage' already contains a definition
for 'LayoutRoot' \SoundBoard\obj\Debug\Cartoons.g.cs
Error 30 The name 'AudioPlayer' does not exist in the current
context \SoundBoard\Cartoons.xaml.cs
Error 7 Type 'SoundBoard.MainPage' already defines a member called
'InitializeComponent' with the same parameter types
\SoundBoard\obj\Debug\Cartoons.g.cs
I'll link my current MainPage and Cartoons and hopefully you guys can help me out.
MainPage.xaml:
<phone:PhoneApplicationPage
x:Class="SoundBoard.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:DataContext="{d:DesignData SampleData/SampleData.xaml}"
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>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="SoundBoard" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="Categories" 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">
<Button Content="Warnings" HorizontalAlignment="Left" Margin="244,304,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click_3"/>
<Button Content="Taunts" HorizontalAlignment="Left" Margin="27,304,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click_2"/>
<Button Content="Cartoons" HorizontalAlignment="Left" Margin="244,123,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click_1"/>
<Button Content="Animals" HorizontalAlignment="Left" Margin="27,123,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click"/>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
MainPage.xaml.cs:
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;
namespace SoundBoard
{
public partial class FirstPage : PhoneApplicationPage
{
public FirstPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Animals.xaml", UriKind.Relative));
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Cartoons.xaml", UriKind.Relative));
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Taunts.xaml", UriKind.Relative));
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Warnings.xaml", UriKind.Relative));
}
}
}
Cartoons.xaml:
<phone:PhoneApplicationPage
x:Class="SoundBoard.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:DataContext="{d:DesignData SampleData/SampleData.xaml}"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot contains the root grid where all other page content is placed-->
<Grid x:Name="LayoutRoot">
<phone:Panorama Title="{Binding Path=LocalizedResources.ApplicationTitle,
Source={StaticResource LocalizedStrings}}">
<!--Panorama item one-->
<phone:PanoramaItem Header="Cartoons">
<Grid>
<Image HorizontalAlignment="Center" Height="431" Margin="10,10,0,0" VerticalAlignment="Top" Width="400" Source="/Assets/cartoon.jpg"/>
</Grid>
</phone:PanoramaItem>
<!--Panorama item two-->
<phone:PanoramaItem Header="Sounds">
<phone:LongListSelector
Margin="0,0,-12,0"
ItemsSource="{Binding Cartoons.Items}"
LayoutMode="Grid"
GridCellSize="150,150"
>
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Background="{StaticResource PhoneAccentBrush}">
<Grid VerticalAlignment="Top" HorizontalAlignment="Right"
Width="40" Height="40" Margin="0,6,6,0">
<Ellipse Stroke="{StaticResource PhoneForegroundBrush}"
StrokeThickness="3" />
<Image Source="Assets/AppBar/Play.png" />
</Grid>
<StackPanel VerticalAlignment="Bottom">
<TextBlock Text="{Binding Title}"
Margin="6,0,0,6"/>
</StackPanel>
</Grid>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</phone:PanoramaItem>
<!--Panorama item three-->
<phone:PanoramaItem Header="Record">
<Grid>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<MediaElement x:Name="AudioPlayer" AutoPlay="False" />
<StackPanel>
<ToggleButton Content="Record"
Checked="RecordAudioChecked"
Unchecked="RecordAudioUnchecked"/>
<Grid Width="200"
Height="200"
Name="ReelGrid"
RenderTransformOrigin=".5,.5">
<Grid.RenderTransform>
<CompositeTransform />
</Grid.RenderTransform>
<Ellipse Fill="{StaticResource PhoneAccentBrush}" />
<Ellipse Height="20"
Width="20"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="0,20,0,20"
VerticalAlignment="Top"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="0,20,0,20"
VerticalAlignment="Bottom"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="0,0,20,0"
HorizontalAlignment="Right"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="20,0,0,0"
HorizontalAlignment="Left"
Fill="{StaticResource PhoneForegroundBrush}" />
</Grid>
<Button Name="PlayAudio" Content="Play" Click="PlayAudioClick" />
</StackPanel>
</Grid>
</Grid>
</phone:PanoramaItem>
</phone:Panorama>
</Grid>
</phone:PhoneApplicationPage>
Cartoons.xaml.cs:
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 SoundBoard.Resources;
using Coding4Fun.Toolkit.Audio;
using Coding4Fun.Toolkit.Audio.Helpers;
using System.IO;
using System.IO.IsolatedStorage;
using Coding4Fun.Toolkit.Controls;
using SoundBoard.ViewModels;
using Newtonsoft.Json;
namespace SoundBoard
{
public partial class Cartoons : PhoneApplicationPage
{
private MicrophoneRecorder _recorder = new MicrophoneRecorder();
private IsolatedStorageFileStream _audioStream;
private string _tempFileName = "tempWav.wav";
public Cartoons()
{
InitializeComponent();
DataContext = App.ViewModel;
BuildLocalizedApplicationBar();
}
// Load data for the ViewModel Items
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LongListSelector selector = sender as LongListSelector;
// verifying our sender is actually a LongListSelector
if (selector == null)
return;
SoundData data = selector.SelectedItem as SoundData;
// verifying our sender is actually SoundData
if (data == null)
return;
if (File.Exists(data.FilePath))
{
AudioPlayer.Source = new Uri(data.FilePath, UriKind.RelativeOrAbsolute);
}
else
{
using (var storageFolder = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = new IsolatedStorageFileStream(data.FilePath, FileMode.Open, storageFolder))
{
AudioPlayer.SetSource(stream);
}
}
}
selector.SelectedItem = null;
}
private void BuildLocalizedApplicationBar()
{
ApplicationBar = new ApplicationBar();
ApplicationBarIconButton recordAudioAppBar =
new ApplicationBarIconButton();
recordAudioAppBar.IconUri = new Uri("/Assets/AppBar/Save.png", UriKind.Relative);
recordAudioAppBar.Text = AppResources.AppBarSave;
recordAudioAppBar.Click += recordAudioAppBar_Click;
ApplicationBar.Buttons.Add(recordAudioAppBar);
ApplicationBar.IsVisible = false;
}
void recordAudioAppBar_Click(object sender, EventArgs e)
{
InputPrompt fileName = new InputPrompt();
fileName.Message = "What should we call the sound?";
fileName.Completed += FileNameCompleted;
fileName.Show();
}
private void FileNameCompleted(object sender, PopUpEventArgs<string, PopUpResult> e)
{
if (e.PopUpResult == PopUpResult.Ok)
{
// Create a sound data object
SoundData soundData = new SoundData();
soundData.FilePath = string.Format("/customAudio/{0}.wav", DateTime.Now.ToFileTime());
soundData.Title = e.Result;
// Save the wav file into the DIR /customAudio/
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) {
if (!isoStore.DirectoryExists("/customAudio/"))
isoStore.CreateDirectory("/customAudio/");
isoStore.MoveFile(_tempFileName, soundData.FilePath);
}
// Add the SoundData to App.ViewModel.CustomSounds
App.ViewModel.CustomSounds.Items.Add(soundData);
// Save the list of CustomSounds to isolatedStorage.ApplicationSettings
var data = JsonConvert.SerializeObject(App.ViewModel.CustomSounds);
IsolatedStorageSettings.ApplicationSettings[SoundModel.CustomSoundKey] = data;
IsolatedStorageSettings.ApplicationSettings.Save();
// We'll need to modify sound model to retrieve CustomSounds
//from isolatedStorage.ApplicationSettings
NavigationService.Navigate(new Uri("", UriKind.RelativeOrAbsolute));
}
}
private void RecordAudioChecked(object sender, RoutedEventArgs e)
{
PlayAudio.IsEnabled = false;
ApplicationBar.IsVisible = false;
RotateCirlce.Begin();
_recorder.Start();
}
private void RecordAudioUnchecked(object sender, RoutedEventArgs e)
{
_recorder.Stop();
SaveTempAudio(_recorder.Buffer);
PlayAudio.IsEnabled = true;
ApplicationBar.IsVisible = true;
RotateCircle.Stop();
}
private void SaveTempAudio(MemoryStream buffer)
{
//defensive...
if (buffer == null)
throw new ArgumentNullException("Attempting a save on empty sound buffer.");
//Clean out hold on audioStream
if (_audioStream != null)
{
AudioPlayer.Stop();
AudioPlayer.Source = null;
_audioStream.Dispose();
}
var bytes = buffer.GetWavAsByteArray(_recorder.SampleRate);
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) {
if (isoStore.FileExists(_tempFileName))
isoStore.DeleteFile(_tempFileName);
_tempFileName = string.Format("{0}.wav", DateTime.Now.ToFileTime());
_audioStream = isoStore.CreateFile(_tempFileName);
_audioStream.Write(bytes, 0, bytes.Length);
//Play ... SetSource of a mediaElement
AudioPlayer.SetSource(_audioStream);
}
}
private void PlayAudioClick(object sender, RoutedEventArgs e)
{
AudioPlayer.Play();
}
}
}
As I said it is probably something dumb but I am really stuck so would really appreciate any advice.
Thanks in advance.
It seems that all the problems reside in auto-generated files Cartoons.g.cs. The only error that points to non fully auto-generated file is this :
The name 'AudioPlayer' does not exist in the current context \SoundBoard\Cartoons.xaml.cs
Which complaining about AudioPlayer doesn't exists when it does exist, declared in Cartoons.xaml. So that's all weird errors.
First thing I will do is clean up (from visual studio, or manually delete bin and debug folders) and rebuild the project, and or even restart Visual Studio. Those steps can fix weird errors most of the time.
The problem is that both Cartoons.xaml and MainPage.xaml have the same line x:Class="SoundBoard.MainPage". I'm not sure but think that Cartoons.xaml should have different value for x:Class attribute

Custom MessageBox Button In WPF

Is there a way to customize button on WPF MessageBox instead "Yes" and "No", I want "Enter" or "Exit" or something like that . All web i search told it is difficult do it rather by creating a window and all but those were 3 or 4 year old answers. Right now is there any easy way to do it ?
You can customize WPF Toolkit Extende MessageBox. Or you can use a custom one WPFCustomMessageBox that ACB suggested.
I know this is a late answer but it can be useful.
I needed the same thing and I found this way and I wanted to share it.
I use a window for this.
In my window, I have a label for the caption and another for the message.
And three buttons (or more if needed).
Here is my window :
<Window x:Class="CapronCAD.LIB.Controls.CapronMessageBox"
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:CapronCAD.LIB.Controls"
mc:Ignorable="d" Height="450" Width="800" WindowStyle="None" WindowStartupLocation="CenterOwner" WindowState="Minimized" ResizeMode="NoResize" ShowInTaskbar="False" AllowsTransparency="True" Background="Transparent">
<Grid x:Name="grdMessageBox" Background="#33000B4B">
<Border BorderBrush="Black" BorderThickness="0" HorizontalAlignment="Center" Height="250" Margin="0" VerticalAlignment="Center" Width="600" Background="White" CornerRadius="5">
<Grid>
<Button x:Name="btnMessageBoxYes" FontWeight="SemiBold" Content="Oui" HorizontalAlignment="Right" VerticalAlignment="Bottom" Style="{DynamicResource ResourceKey=Capron_Violet_ButtonStyle}" Margin="0,0,30,30" Width="60" Click="btnMessageBoxYes_Click"/>
<Button x:Name="btnMessageBoxNo" FontWeight="SemiBold" Content="Non" HorizontalAlignment="Right" VerticalAlignment="Bottom" Style="{DynamicResource ResourceKey=Capron_Violet_ButtonStyle}" Margin="0,0,103,30" Width="60" Background="#FFCFC9FF" Foreground="#FF6F5DF5" Click="btnMessageBoxNo_Click"/>
<TextBlock x:Name="tbMessageBoxCaption" FontWeight="SemiBold" Margin="30,43,10,0" TextWrapping="Wrap" Text="-" VerticalAlignment="Top" FontFamily="Poppins" FontSize="14"/>
<TextBlock x:Name="tbMessageBoxMessage" Margin="30,80,10,0" TextWrapping="Wrap" Text="-" VerticalAlignment="Top" FontFamily="Poppins"/>
<Image x:Name="imgMessageBoxCancel" HorizontalAlignment="Right" Height="18" Margin="0,19,30,0" VerticalAlignment="Top" Width="18" Source="/CapronCAD.LIB;component/Resources/CloseBlack.png" MouseLeftButtonUp="imgMessageBoxCancel_MouseLeftButtonUp"/>
<Button x:Name="btnMessageBoxClose" FontWeight="SemiBold" Content="Fermer" HorizontalAlignment="Center" VerticalAlignment="Bottom" Style="{DynamicResource ResourceKey=Capron_Violet_ButtonStyle}" Margin="0,0,0,30" Visibility="Collapsed" Click="btnMessageBoxClose_Click"/>
</Grid>
</Border>
</Grid>
Here is the simple method which shows the window as a dialog :
internal static System.Windows.Forms.DialogResult ShowCustomMessageBox(string message, string caption = "Default caption", bool dialog = true)
{
Controls.CapronMessageBox mb = new Controls.CapronMessageBox(caption, message, dialog);
mb.Topmost = true;
mb.WindowState = WindowState.Maximized;
mb.ShowDialog();
if (mb.DialogResult == null)
return System.Windows.Forms.DialogResult.None;
else if (mb.DialogResult == true)
return System.Windows.Forms.DialogResult.Yes;
else
return System.Windows.Forms.DialogResult.No;
}
Here is the code behind the window :
public partial class CapronMessageBox: Window
{
public CapronMessageBox(string caption, string message, bool dialog)
{
InitializeComponent();
tbMessageBoxCaption.Text = caption;
tbMessageBoxMessage.Text = message;
if (!dialog)
{
btnMessageBoxClose.Visibility = Visibility.Visible;
btnMessageBoxNo.Visibility = Visibility.Collapsed;
btnMessageBoxYes.Visibility = Visibility.Collapsed;
}
}
private void btnMessageBoxNo_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void imgMessageBoxCancel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
this.Close();
}
private void btnMessageBoxYes_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
private void btnMessageBoxClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
And here how I call it :
if (UserMethods.ShowCustomMessageBox("Do you want to save changes?", "Are you sure?", false) == DialogResult.Yes)
{
btnSave_Click(btnSave, null);
}
And here is how it seems :

make data grid visible on click

I have this data grid where I am placing all my buttons
<Grid x:Name="ButtonGrid" HorizontalAlignment="Left" Margin="0,90,0,4" Width="186">
<Button x:Name="B1" Content="B1" Height="18" Margin="73,0,59,16" VerticalAlignment="Bottom" Click="B1"/>
<Button x:Name="B2" Content="B2" Height="18" Margin="0,0,-2,16" VerticalAlignment="Bottom" Click="B2_Click" HorizontalAlignment="Right" Width="57"/>
</Grid>
I have the grid collapased on start. But when a button {testGrid} is clicked, I want the grid to ne visible.
Here is my code
namespace project.Test
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
EDUTED
private void testGrid_Click(object sender, System.Windows.RoutedEventArgs e)
{
FrameworkElement ButtonGrid = (sender as FrameworkElement).FindName("ButtonGrid") as FrameworkElement;
if ( ButtonGrid.Visibility == System.Windows.Visibility.Collapsed)
ButtonGrid.Visibility = System.Windows.Visibility.Visible;
else
ButtonGrid.Visibility = System.Windows.Visibility.Collapsed;
}
}
}
I think if you move your Grid outside of your DataTemplate it will work. :)
However if you really need to put it in a DataTemplate, as long as your Button is at the same level as the Grid, you should still be able to find it.
Say your xaml code looks like this,
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="controlstoryboardactionrefissue.MainPage" Width="640" Height="480">
<UserControl.Resources>
<DataTemplate x:Key="DataTemplate1">
<Grid x:Name="myGrid" Height="128" Background="#FFE7C0C0" Width="333">
<Button x:Name="myButton" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="31,29,0,0" Click="myButton_Click" />
</Grid>
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<ContentControl HorizontalAlignment="Left" VerticalAlignment="Top" Margin="175,198,0,0" ContentTemplate="{StaticResource DataTemplate1}" />
</Grid>
</UserControl>
Then the code behind,
private void myButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
var myButton = (Button)sender;
var grid = myButton.Parent as Grid;
if (grid != null)
{
// do stuff
}
}
Hope it helps. :)

WebBrowser control not working

I'm developing a Windows Phone 7 app with C#.
I'm trying to do a login with Facebook Login Page.
Here is my cs source:
namespace FacebookLogin
{
public partial class MainPage : PhoneApplicationPage
{
private const string appId = "xxx";
private const string apiKey = "xxx"; //insert your apps key here... see developers.facebook.com/setup/
private readonly string[] extendedPermissions = new[] { "user_about_me" };
private bool loggedIn = false;
private FacebookClient fbClient;
PhoneApplicationService appService = PhoneApplicationService.Current;
// Constructor
public MainPage()
{
InitializeComponent();
fbClient = new FacebookClient();
FacebookLoginBrowser.Loaded += new RoutedEventHandler(FacebookLoginBrowser_Loaded);
//FacebookLoginBrowser.Navigated +=new EventHandler<System.Windows.Navigation.NavigationEventArgs>(FacebookLoginBrowser_Navigated);
}
private void FacebookLoginBrowser_Loaded(object sender, RoutedEventArgs e)
{
if (!loggedIn)
{
LoginToFacebook();
}
}
private void FacebookLoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
if (FacebookOAuthResult.TryParse(e.Uri, out oauthResult))
{
if (oauthResult.IsSuccess)
{
fbClient = new FacebookClient(oauthResult.AccessToken);
loggedIn = true;
loginSucceeded();
}
else
{
MessageBox.Show(oauthResult.ErrorDescription);
}
}
}
private void LoginToFacebook()
{
TitlePanel.Visibility = Visibility.Visible;
FacebookLoginBrowser.Visibility = Visibility.Visible;
InfoPanel.Visibility = Visibility.Collapsed;
var loginParameters = new Dictionary<string, object>
{
{ "response_type", "token" }
// { "display", "touch" } // by default for wp7 builds only (in Facebook.dll), display is set to touch.
};
var navigateUrl = FacebookOAuthClient.GetLoginUrl(appId, null, extendedPermissions, loginParameters);
FacebookLoginBrowser.Navigate(navigateUrl);
}
// At this point we have an access token so we can get information from facebook
private void loginSucceeded()
{
TitlePanel.Visibility = Visibility.Visible;
FacebookLoginBrowser.Visibility = Visibility.Collapsed;
InfoPanel.Visibility = Visibility.Visible;
fbClient.GetCompleted +=
(o, e) =>
{
if (e.Error == null)
{
var result = (IDictionary<string, object>)e.GetResultData();
Dispatcher.BeginInvoke(() => MyData.ItemsSource = result);
}
else
{
MessageBox.Show(e.Error.Message);
}
};
fbClient.GetAsync("/me");
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs args)
{
appService.State["fbClient"] = fbClient;
base.OnNavigatedFrom(args);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs args)
{
base.OnNavigatedTo(args);
}
}
}
And here is my XAML code:
<phone:PhoneApplicationPage
x:Class="FacebookLogin.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">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28" Visibility="Collapsed">
<TextBlock x:Name="ApplicationTitle" Text="MI APLICACIÓN" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="nombre de la página" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:WebBrowser HorizontalAlignment="Left" Name="FacebookLoginBrowser" Height="607" VerticalAlignment="Top" Width="450" />
<Grid x:Name="InfoPanel" Grid.Row="1">
<ListBox x:Name="MyData" Height="657" HorizontalAlignment="Stretch" VerticalAlignment="Top">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" MinWidth="500">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Key}"/>
<TextBlock Grid.Column="1" Text="{Binding Value}" TextWrapping="Wrap"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
</Grid>
<!--<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Botón 1"/>
<shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Botón 2"/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text="Elemento de menú 1"/>
<shell:ApplicationBarMenuItem Text="Elemento de menú 2"/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>-->
</phone:PhoneApplicationPage>
Where is the error? FacebookLoginBrowser_Navigated isn't never reached.
Here's the answer (and I knew it before even looking at your code, but I did doublecheck). The WP7 Browser control defaults to having JavaScript disabled (why they did that is beyond me). SO, you need to set the "IsScriptEnabled" property of the web browser control to True (you can do this in code or in XAML), and then I bet everything will work.
You have your FacebookLoginBrowser_Navigated event handler commented out. That is the correct one to use. Not a RoutedEventHandler just an EventHandler.
Also it might not be a bad idea just to set the eventhandler in design view on the browser control if it's not absolutely necessary to dynamically create the event.

Categories

Resources