I have created a barcode scanner in C# for Windows Phone 8 using ZXing.NET. It worked fine but since this morning, it displays the error Unable to initialize camera. I haven't changed the code inside the page. Anyone familair with this problem or knows a solution?
C#:
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.Devices;
using System.Threading;
using System.Windows.Media.Imaging;
using ZXing;
using System.Windows.Threading;
using ZXing.QrCode;
using System.Xml.Linq;
namespace PhoneApp2
{
public partial class Scan : PhoneApplicationPage
{
private PhotoCamera _phoneCamera;
private IBarcodeReader _barcodeReader;
private DispatcherTimer _scanTimer;
private WriteableBitmap _previewBuffer;
public Scan()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
// Initialize the camera object
_phoneCamera = new PhotoCamera();
_phoneCamera.Initialized += cam_Initialized;
CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed;
//Display the camera feed in the UI
viewfinderBrush.SetSource(_phoneCamera);
// This timer will be used to scan the camera buffer every 250ms and scan for any barcodes
_scanTimer = new DispatcherTimer();
_scanTimer.Interval = TimeSpan.FromMilliseconds(250);
_scanTimer.Tick += (o, arg) => ScanForBarcode();
base.OnNavigatedTo(e);
}
void CameraButtons_ShutterKeyHalfPressed(object sender, EventArgs e)
{
_phoneCamera.Focus();
}
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
//we're navigating away from this page, we won't be scanning any barcodes
_scanTimer.Stop();
if (_phoneCamera != null)
{
// Cleanup
_phoneCamera.Dispose();
_phoneCamera.Initialized -= cam_Initialized;
CameraButtons.ShutterKeyHalfPressed -= CameraButtons_ShutterKeyHalfPressed;
}
}
void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
{
try
{
if (e.Succeeded)
{
this.Dispatcher.BeginInvoke(delegate()
{
_phoneCamera.FlashMode = FlashMode.Off;
_previewBuffer = new WriteableBitmap((int)_phoneCamera.PreviewResolution.Width, (int)_phoneCamera.PreviewResolution.Height);
_barcodeReader = new BarcodeReader();
// By default, BarcodeReader will scan every supported barcode type
// If we want to limit the type of barcodes our app can read,
// we can do it by adding each format to this list object
//var supportedBarcodeFormats = new List<BarcodeFormat>();
//supportedBarcodeFormats.Add(BarcodeFormat.QR_CODE);
//supportedBarcodeFormats.Add(BarcodeFormat.DATA_MATRIX);
//_bcReader.PossibleFormats = supportedBarcodeFormats;
var supportedBarcodeFormats = new List<BarcodeFormat>();
supportedBarcodeFormats.Add(BarcodeFormat.EAN_8);
supportedBarcodeFormats.Add(BarcodeFormat.EAN_13);
supportedBarcodeFormats.Add(BarcodeFormat.UPC_A);
supportedBarcodeFormats.Add(BarcodeFormat.UPC_E);
supportedBarcodeFormats.Add(BarcodeFormat.UPC_EAN_EXTENSION);
_barcodeReader.PossibleFormats = supportedBarcodeFormats;
_barcodeReader.TryHarder = true;
_barcodeReader.ResultFound += _bcReader_ResultFound;
_scanTimer.Start();
});
}
else
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Unable to initialize the camera");
});
}
}
catch (Exception myExc)
{
Console.WriteLine(myExc.Message);
}
}
void _bcReader_ResultFound(Result obj)
{
// If a new barcode is found, vibrate the device and display the barcode details in the UI
if (!obj.Text.Equals(tbBarcodeData.Text))
{
VibrateController.Default.Start(TimeSpan.FromMilliseconds(100));
tbBarcodeType.Text = obj.BarcodeFormat.ToString();
tbBarcodeData.Text = obj.Text;
}
}
private void ScanForBarcode()
{
if (_phoneCamera.IsFocusSupported == true)
{
//Focus when a capture is not in progress.
try
{
_phoneCamera.Focus();
}
catch (Exception focusError)
{
// Cannot focus when a capture is in progress.
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = focusError.Message;
});
}
}
//grab a camera snapshot
_phoneCamera.GetPreviewBufferArgb32(_previewBuffer.Pixels);
_previewBuffer.Invalidate();
//scan the captured snapshot for barcodes
//if a barcode is found, the ResultFound event will fire
_barcodeReader.Decode(_previewBuffer);
}
}
}
XAML:
<phone:PhoneApplicationPage
x:Class="PhoneApp2.Scan"
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">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<Canvas x:Name="viewfinderCanvas">
<!--Camera viewfinder -->
<Canvas.Background>
<VideoBrush x:Name="viewfinderBrush">
<VideoBrush.RelativeTransform>
<CompositeTransform
x:Name="viewfinderTransform"
CenterX="0.5"
CenterY="0.5"
Rotation="90"/>
</VideoBrush.RelativeTransform>
</VideoBrush>
</Canvas.Background>
<TextBlock Height="40" HorizontalAlignment="Left" x:Name="txtDebug" VerticalAlignment="Top" Width="462" FontSize="24" FontWeight="ExtraBold" Canvas.Left="10" Canvas.Top="618" />
<Path Data="M443.885,209.007 L248.921,209.007" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="5" Canvas.Left="26" Canvas.Top="201.36" Width="143.77"/>
<Path Data="M443.885,209.007 L248.921,209.007" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="5" Canvas.Left="310.23" Canvas.Top="201.36" Width="143.77"/>
<Path Data="M443.885,209.007 L248.921,209.007" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="5" Canvas.Left="310.23" Canvas.Top="493.36" Width="143.77"/>
<Path Data="M443.885,209.007 L248.921,209.007" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="5" Canvas.Left="26" Canvas.Top="493.36" Width="143.77"/>
<Path Data="M387.983,239.245 L387.983,399.76" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="101.779" Canvas.Left="449" Canvas.Top="199" Width="5"/>
<Path Data="M387.983,239.245 L387.983,399.76" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="101.779" Canvas.Left="26" Canvas.Top="399.081" Width="5"/>
<Path Data="M387.983,239.245 L387.983,399.76" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="101.779" Canvas.Left="26" Canvas.Top="199" Width="5"/>
<Path Data="M387.983,239.245 L387.983,399.76" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="101.779" Canvas.Left="449" Canvas.Top="399.081" Width="5"/>
</Canvas>
<!--Used for debugging >-->
<StackPanel Grid.Row="1" Margin="20, 0">
<TextBlock x:Name="tbBarcodeType" FontWeight="ExtraBold" />
<TextBlock x:Name="tbBarcodeData" FontWeight="ExtraBold" TextWrapping="Wrap" />
</StackPanel>
</Grid>
</phone:PhoneApplicationPage>
Related
I want to animate, a rectangle in my canvas to go up. This should happen in the coder behind. In the end, I want to let the rectangle go up and down in while loop, but I can't even get it to go in one direction.
Xaml:
<Window x:Class="WpfApp.View.CPR"
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:WpfApp.View"
mc:Ignorable="d"
Title="CPR" Height="250" Width="210">
<Grid Background="Black">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="0.5*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1">
<TextBlock Text="Counter" HorizontalAlignment="Center" Grid.Column="1" Grid.Row="0" Background="Black" Foreground="White"/>
<TextBlock Text="" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center" Grid.Column="1" Grid.Row="0" Background="Black" Foreground="White"/>
</StackPanel>
<Canvas Grid.Column="0" Grid.Row="0" Grid.RowSpan="2">
<Rectangle Fill="Red" Height="2" Width="110" Canvas.Top="20" Canvas.Left="23.75"/>
<Rectangle Fill="LawnGreen" Height="20" Width="5" Canvas.Top="170" Canvas.Left="76.25" x:Name="line"/>
<Rectangle Fill="Red" Height="2" Width="110" Canvas.Top="190" Canvas.Left="23.75"/>
</Canvas>
<StackPanel Grid.Row="1"/>
</Grid>
</Window>
In my code, I tried something from the internet. I actually have no clue.
Code:
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApp.View
{
/// <summary>
/// Interaktionslogik für CPR.xaml
/// </summary>
public partial class CPR : Window
{
public CPR()
{
InitializeComponent();
var translation = new TranslateTransform(0, -170);
var animation = new DoubleAnimation();
animation.Duration = new Duration(new TimeSpan(625));
animation.RepeatBehavior = RepeatBehavior.Forever;
animation.From = 76.25;
animation.To = 20;
var board = new Storyboard();
board.Children.Add(animation);
Storyboard.SetTarget(board, translation);
Storyboard.SetTargetProperty(board, new PropertyPath(Rectangle.Y));
line.Loaded += delegate (object sender, RoutedEventArgs e)
{
line.BeginStoryboard(board);
};
}
}
}
Thanks for your help!
You would simply animate the Canvas.Top property.
The following example would animate the Top value from 100 to 200 within 1 second, then back from 200 to 100, forever.
<Canvas>
<Rectangle x:Name="rectangle" Canvas.Left="100" Canvas.Top="100"
Width="100" Height="100" Fill="Red"/>
</Canvas>
In code behind:
var topAnimation = new DoubleAnimation
{
From = 100,
To = 200,
Duration = TimeSpan.FromSeconds(1),
AutoReverse = true,
RepeatBehavior = RepeatBehavior.Forever
};
rectangle.BeginAnimation(Canvas.TopProperty, topAnimation);
I am creating WPF universal app game "Pong" on VS 2015.
Design:
<Page
x:Class="Pong.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Pong"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Canvas Name="MainCanavas" HorizontalAlignment="Center" Height="640" VerticalAlignment="Center" Width="1024" Background="Black">
<Rectangle Height="100" Width="20" Fill="White" Name="LeftPad" Canvas.Top="{Binding YPosition}" HorizontalAlignment="Center" />
<Rectangle Height="100" Width="20" Fill="White" Name="RightPad" Canvas.Top="{Binding YPosition}" Canvas.Left="1005"></Rectangle>
<Line X1="500" X2="500" Y2="630" Y1="15" StrokeThickness="5" StrokeDashArray="2" Stroke="White"></Line>
<Ellipse Width="30" Height="30" Name="Ball" Fill="White" StrokeThickness="0.1" DataContext="{Binding Path=ball}" Canvas.Left="{Binding X}" Canvas.Top="{Binding Y}" RenderTransformOrigin="0.48,0.587"></Ellipse>
<TextBlock x:Name="LeftScore" Canvas.Left="374" TextWrapping="Wrap" Text="0" Foreground="White" Canvas.Top="10" Height="134" Width="62" FontSize="96" HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center" RenderTransformOrigin="0.481,0.499"/>
<TextBlock x:Name="RightScore" Canvas.Left="564" TextWrapping="Wrap" Text="0" Foreground="White" Canvas.Top="10" Height="134" Width="62" FontSize="96" HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center" RenderTransformOrigin="0.481,0.499"/>
</Canvas>
It's a 2 player game, so I wrote two paddle events, for left and right pads:
private void LeftPad_KeyDown(object sender, KeyEventArgs e)
{
// Left pad events
if (e.VirtualKey == VirtualKey.W)
{
leftPad.YPosition -= padMoveBy;
}
if (e.VirtualKey == VirtualKey.S)
{
leftPad.YPosition += padMoveBy;
}
}
private void RightPad_KeyDown(object sender, KeyEventArgs e)
{
// Right pad events
if (e.VirtualKey == VirtualKey.Up)
{
rightPad.YPosition -= padMoveBy;
}
if (e.VirtualKey == VirtualKey.Down)
{
rightPad.YPosition += padMoveBy;
}
}
Main contructor:
public MainPage()
{
this.InitializeComponent();
CoreWindow.GetForCurrentThread().KeyDown += LeftPad_KeyDown;
CoreWindow.GetForCurrentThread().KeyDown += RightPad_KeyDown;
Ball.DataContext = ball;
LeftPad.DataContext = leftPad;
RightPad.DataContext = rightPad;
LeftScore.DataContext = leftScore;
RightScore.DataContext = rightScore;
}
When I run the program, I can move just one paddle at the time, even though I have two events.
Help would be nice...
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
My (first) Windows Phone app keeps crashing when the code takes the selection from a ListPicker, and a webbrowser navigates to that selection. It builds without errors, but crashed when I run it and press the button. I am a beginner when it comes to coding, so please dumb-down your answers :)
Heres my code:
XAML:
<phone:PhoneApplicationPage
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"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
x:Class="SecurityCamera.Page1"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Name="ListPickerItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="10 0 0 0"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Name="ListPickerFullModeItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" 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 Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="Security Camera Access" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="Specify IP" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Margin="12,138,12,0" Grid.RowSpan="2" Opacity="0.99">
<TextBox x:Name="box1" HorizontalAlignment="Left" Height="70" Margin="31,172,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<TextBox x:Name="box2" HorizontalAlignment="Left" Height="70" Margin="31,242,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<TextBox x:Name="box3" HorizontalAlignment="Left" Height="70" Margin="31,312,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<TextBox x:Name="box4" HorizontalAlignment="Left" Height="70" Margin="31,382,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<Button Content="Connect" HorizontalAlignment="Left" Height="80" Margin="84,527,0,0" VerticalAlignment="Top" Width="305" Click="Button_Click_1"/>
<Button Content="Save" HorizontalAlignment="Left" Height="80" Margin="84,457,0,0" VerticalAlignment="Top" Width="305" Click="Button_Click_2"/>
<TextBlock HorizontalAlignment="Left" Margin="10,119,0,0" TextWrapping="Wrap" Text="Write IP's below to save - Include http:// before all addresses!" VerticalAlignment="Top"/>
</Grid>
<toolkit:ListPicker x:Name="defaultPicker" SelectionChanged="OnListPickerChanged" ExpansionMode="FullScreenOnly" Header="Saved IP's:" Margin="72,0,72,489" Grid.Row="1"/>
<phone:WebBrowser x:Name="webBrowser" HorizontalAlignment="Left" Margin="12,143,0,0" VerticalAlignment="Top" Width="456" Grid.RowSpan="2" Height="615" Opacity="100" Visibility="Visible"/>
</Grid>
</phone:PhoneApplicationPage>
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 System.Xml;
using System.IO.IsolatedStorage;
using System.IO;
namespace SecurityCamera
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
defaultPicker.ItemsSource = new List<string>() { { box1.Text }, { box2.Text }, { box3.Text }, { box4.Text } };
webBrowser.Visibility = System.Windows.Visibility.Collapsed;
// DEBUG MESSAGE - DELETE
MessageBox.Show("Visibility set to Collapsed (startup)");
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
------------------------THIS IS WHERE IT CRASHES --------------------------
//DEBUG MESSAGE - DELETE
MessageBox.Show("Button Pressed!");
string selectedItem;
selectedItem = (sender as ListPicker).SelectedItem.ToString();
// Do what you want with selectedItem
webBrowser.Navigate(new Uri(selectedItem));
//DEBUG MESSAGE - DELETE
MessageBox.Show("webBrowser.Navigate Executed...Making Visible");
webBrowser.Visibility = System.Windows.Visibility.Visible;
// DEBUG MESSAGE - DELETE
MessageBox.Show("webBrowser navigation sent - webBrowser Visibility set to Visible - Button Press");
}
private void OnListPickerChanged(object sender, SelectionChangedEventArgs e)
{
string selectedItem;
selectedItem = (sender as ListPicker).SelectedItem.ToString();
// Do what you want with selectedItem
// webBrowser.Navigate(new Uri(selectedItem));
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
defaultPicker.ItemsSource = new List<string>() { { box1.Text }, { box2.Text }, { box3.Text }, { box4.Text } };
// Write Text's into param
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
//create new file
using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("ip1.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage)))
{
string someTextData = "{ box1.Text }";
writeFile.WriteLine(someTextData);
writeFile.Close();
}
}
}
}
I believe this cast is failing:
selectedItem = (sender as ListPicker).SelectedItem.ToString();
instead try:
selectedItem = defaultPicker.SelectedItem.ToString();
I'm relatively new to WPF, I come from a WinForms background, I'm trying to implement a coverflow, and I don't fully understand the example, from I what I see, I add the paths to my images to a StringCollection.
This is what I have right now :
public MainWindow()
{
InitializeComponent();
elementFlow1.Layout = new CoverFlow();
StringCollection itemssource = new StringCollection();
itemssource.Add(#"Images\1.png");
itemssource.Add(#"Images\2.png");
elementFlow1.SelectedIndex = 0;
elementFlow1.ItemsSource = itemssource;
}
And I have the ElementFlow defined in XAML like so:
<fluidkit:ElementFlow Grid.Row="1" Height="194" Name="elementFlow1" VerticalAlignment="Top" Width="503" />
Lo and behold, when I run it, nothing happens.
Can someone please explain how I'm supposed to use ElementFlow? The example doesn't really "explain" it very well.
You're missing a key step. The ElementFlow control displays UIElements, not strings. You have a list of strings that contain the logical file location of the image files. Now you need to convert that collection of strings to a collection of DataTemplates. If you look in the sample xaml file, you'll see this section:
<DataTemplate x:Key="TestDataTemplate"
DataType="{x:Type sys:String}">
<Border x:Name="ElementVisual"
Background="White"
Padding="5"
BorderThickness="5"
BorderBrush="LightGray"
Grid.Row="0">
<Image Source="{Binding}"
Stretch="Fill" />
</Border>
</DataTemplate>
That section essentially takes a string input and converts it to a DataTemplate. This is done by setting the ItemTemplate property to this DataTemplate resource.
You'll probably be better off manipulating this control in XAML rather than code-behind. Things are easier that way (in my opinion anyways).
Hope this helps.
I would recommend following the Examples provided:
http://fluidkit.codeplex.com/SourceControl/latest#FluidKit.Samples/ElementFlow/ElementFlowExample.xaml.cs
This is my mod, Project named: ElementFlowExample
namespace ElementFlowExample
{
#region Using Statements:
using System;
using System.Diagnostics;
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.Media.Media3D;
using System.Windows.Navigation;
using System.Windows.Shapes;
using FluidKit.Controls;
using FluidKit.Showcase.ElementFlow;
#endregion
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Fields:
private StringCollection _dataSource;
private LayoutBase[] _layouts = {
new Wall(),
new SlideDeck(),
new CoverFlow(),
new Carousel(),
new TimeMachine2(),
new ThreeLane(),
new VForm(),
new TimeMachine(),
new RollerCoaster(),
new Rolodex(),
};
private Random _randomizer = new Random();
private int _viewIndex;
#endregion
#region Properties:
#endregion
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_elementFlow.Layout = _layouts[3];
_currentViewText.Text = _elementFlow.Layout.GetType().Name;
_selectedIndexSlider.Maximum = _elementFlow.Items.Count - 1;
_elementFlow.SelectionChanged += EFSelectedIndexChanged;
_elementFlow.SelectedIndex = 0;
_dataSource = FindResource("DataSource") as StringCollection;
}
private void EFSelectedIndexChanged(object sender, SelectionChangedEventArgs e)
{
Debug.WriteLine((sender as ElementFlow).SelectedIndex);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Key == Key.F12)
{
_viewIndex = (_viewIndex + 1) % _layouts.Length;
_elementFlow.Layout = _layouts[_viewIndex];
_currentViewText.Text = _elementFlow.Layout.GetType().Name;
}
}
private void ChangeSelectedIndex(object sender, RoutedPropertyChangedEventArgs<double> args)
{
_elementFlow.SelectedIndex = (int)args.NewValue;
}
private void RemoveCard(object sender, RoutedEventArgs args)
{
if (_elementFlow.Items.Count > 0)
{
_dataSource.RemoveAt(_randomizer.Next(_dataSource.Count));
// Update selectedindex slider
_selectedIndexSlider.Maximum = _elementFlow.Items.Count - 1;
}
}
private void AddCard(object sender, RoutedEventArgs args)
{
Button b = sender as Button;
int index = _randomizer.Next(_dataSource.Count);
if (b.Name == "_regular")
{
_dataSource.Insert(index, "Images/01.jpg");
}
else
{
_dataSource.Insert(index, string.Format("Images/{0:00}", _randomizer.Next(1, 12)) + ".jpg");
}
// Update selectedindex slider
_selectedIndexSlider.Maximum = _elementFlow.Items.Count - 1;
}
} // END of Class...
} // END of Namespace...
<Window x:Class="ElementFlowExample.MainWindow"
xmlns:b="clr-namespace:ElementFlowExample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:FluidKit.Showcase.ElementFlow"
xmlns:Controls="clr-namespace:FluidKit.Controls;assembly=FluidKit"
Loaded="Window_Loaded"
Title="ElementFlow - FluidKit"
WindowStartupLocation="CenterScreen"
Width="1280"
Height="720">
<Window.Resources>
<local:StringCollection x:Key="DataSource" />
<LinearGradientBrush x:Key="ReflectionBrush" StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="#7F000000" />
<GradientStop Offset=".5" Color="Transparent" />
</LinearGradientBrush>
<DataTemplate x:Key="TestDataTemplate"
DataType="{x:Type sys:String}">
<Border x:Name="ElementVisual"
Background="White"
Padding="5"
BorderThickness="5"
BorderBrush="LightGray"
Grid.Row="0">
<Image Source="{Binding}"
Stretch="Fill" />
</Border>
</DataTemplate>
<DataTemplate x:Key="TestDataTemplate_Reflection">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.5*" />
<RowDefinition Height="0.5*" />
</Grid.RowDefinitions>
<Border x:Name="ElementVisual"
BorderThickness="2"
BorderBrush="LightYellow"
Background="Black"
Padding="2">
<Image Source="{Binding}"
Stretch="Fill" />
</Border>
<Rectangle OpacityMask="{StaticResource ReflectionBrush}"
Grid.Row="1"
Height="{Binding ActualHeight, ElementName=ElementVisual}">
<Rectangle.Fill>
<VisualBrush Visual="{Binding ElementName=ElementVisual}">
<VisualBrush.RelativeTransform>
<ScaleTransform ScaleX="1"
ScaleY="-1"
CenterX="0.5"
CenterY="0.5" />
</VisualBrush.RelativeTransform>
</VisualBrush>
</Rectangle.Fill>
</Rectangle>
</Grid>
</DataTemplate>
<DataTemplate x:Key="ItemTemplate">
<Border BorderBrush="#FFB1B1B1"
BorderThickness="2"
Background="#7FFFFFFF"
Padding="0,20,0,0"
CornerRadius="3">
<Image Source="{Binding Image}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Stretch="Fill" />
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Vertical"
Grid.Row="1"
Grid.Column="0"
Margin="5">
<Label Content="SelectedIndex" />
<Slider x:Name="_selectedIndexSlider"
Minimum="0"
Value="0"
ValueChanged="ChangeSelectedIndex" />
<Label Content="TiltAngle" />
<Slider x:Name="_tiltAngleSlider"
Minimum="0"
Maximum="90"
Value="45" />
<Label Content="ItemGap" />
<Slider x:Name="_itemGapSlider"
Minimum="0.25"
Maximum="3"
Value="0.65" />
</StackPanel>
<StackPanel Orientation="Vertical"
Grid.Row="1"
Grid.Column="1"
Margin="5">
<Label Content="FrontItemGap" />
<Slider x:Name="_frontItemGapSlider"
Minimum="0"
Maximum="4.0"
Value="1.5"/>
<Label Content="PopoutDistance" />
<Slider x:Name="_popoutDistanceSlider"
Minimum="-2.0"
Maximum="2.0"
Value="-0.3" />
<StackPanel Orientation="Horizontal"
Margin="0,10,0,0">
<Button x:Name="_regular"
Click="AddCard"
Margin="0,0,10,0"
Content="Add Type A" />
<Button x:Name="_alert"
Click="AddCard"
Margin="0,0,10,0"
Content="Add Type B" />
<Button Click="RemoveCard"
Margin="0,0,10,0"
Content="Remove" />
</StackPanel>
</StackPanel>
<Controls:ElementFlow x:Name="_elementFlow"
Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="2"
ItemsSource="{DynamicResource DataSource}"
ItemTemplate="{DynamicResource TestDataTemplate}"
TiltAngle="{Binding Value, ElementName=_tiltAngleSlider}"
ItemGap="{Binding Value, ElementName=_itemGapSlider}"
FrontItemGap="{Binding Value, ElementName=_frontItemGapSlider}"
PopoutDistance="{Binding Value, ElementName=_popoutDistanceSlider}"
ElementWidth="300"
ElementHeight="200"
SelectedIndex="3">
<Controls:ElementFlow.Layout>
<Controls:CoverFlow />
</Controls:ElementFlow.Layout>
<Controls:ElementFlow.Background>
<LinearGradientBrush EndPoint="0.5,1"
StartPoint="0.5,0">
<GradientStop Color="#FF181818" />
<GradientStop Color="#FF7A7A7A"
Offset="0.5" />
<GradientStop Color="#FF1A1A1A"
Offset="1" />
</LinearGradientBrush>
</Controls:ElementFlow.Background>
<Controls:ElementFlow.Camera>
<PerspectiveCamera FieldOfView="60"
Position="0,3,6"
LookDirection="0,-3,-6" />
</Controls:ElementFlow.Camera>
</Controls:ElementFlow>
<TextBlock Text="F12 to switch views"
Foreground="White"
FontWeight="Bold"
VerticalAlignment="Top"
HorizontalAlignment="Right"
Margin="10"
Grid.Row="0"
Grid.Column="1" />
<TextBlock x:Name="_currentViewText"
Foreground="White"
FontWeight="Bold"
VerticalAlignment="Top"
HorizontalAlignment="Right"
Margin="10,30,10,10"
Grid.Row="0"
Grid.Column="1" />
</Grid>
</Window>
Hope this helps!