wpf Can i display images in DocumentViewer? - c#

I want to display xps Image in DocumentViewer, but without success.
Does DocumentViewer support displaying images?
If it is possible to display a picture in DocumentView, how can I do it?
Any reply will be helpful.
My code is as follows:
<StackPanel Orientation="Horizontal" >
<FlowDocumentReader Height="150" Width="170">
<FlowDocument Name="flowDocument" ColumnWidth="400" FontSize="14" FontFamily="Georgia">
<Paragraph>
<Grid>
<Image Source="C:\Users\Admin\Downloads\XpsTest-main\XpsTest-main\33.jpg" Width="200" Height="200" />
<TextBlock Text="Hello World!" HorizontalAlignment="Center" VerticalAlignment="Top" Foreground="Red" />
</Grid>
</Paragraph>
</FlowDocument>
</FlowDocumentReader>
<StackPanel>
<Button Click="Button_Click" Content="save"/>
<Button Click="Button_Click_1" Content="show"/>
</StackPanel>
<DocumentViewer Name="viewer" Width="600"/>
</StackPanel>
C#
using System.IO;
using System.IO.Packaging;
using System.Printing;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using System.Windows.Xps.Serialization;
namespace XpsTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void PrintVisual(Visual visual)
{
PrintDocumentImageableArea imageArea = null;
XpsDocumentWriter xpdw = PrintQueue.CreateXpsDocumentWriter(ref imageArea);
if (xpdw != null)
{
xpdw.Write(visual);
}
}
public static void SaveAsXps(string path, FlowDocument document)
{
using (var package = Package.Open(path, FileMode.Create))
{
using (var xpsDocument = new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum))
{
var xpsSerializationManager = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false);
var documentPaginator = ((IDocumentPaginatorSource)document).DocumentPaginator;
xpsSerializationManager.SaveAsXaml(documentPaginator);
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SaveAsXps(#"C:\Users\Admin\Desktop\temp.xps", flowDocument);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
XpsDocument xpsDocument = new XpsDocument(#"C:\Users\Admin\Desktop\temp.xps", FileAccess.Read);
FixedDocumentSequence fds = xpsDocument.GetFixedDocumentSequence();
viewer.Document = fds;
}
}
}
Test the above code, the picture cannot be displayed normally in DocumentView.

This is caused by an security update from Windows
KB5022083 Change in how WPF-based applications render XPS documents
XPS documents ... . Additionally, some inline images may not display correctly when XPS documents are loaded into WPF-based readers.
This regression was introduced in the December 13, 2022, cumulative security updates for .NET and .NET Framework.
Microsoft is actively investigating an additional update which restores compatibility while also resolving the underlying security issue.

I think the problem here is likely to be because Image is a UI control.
You could try putting it in a blockUIcontainer.
Try:
<FlowDocument Name="flowDocument" ColumnWidth="400" FontSize="14" FontFamily="Georgia">
<Paragraph>
<BlockUIContainer>
<Image Source="C:\Users\Admin\Downloads\XpsTest-main\XpsTest-main\33.jpg" Width="200" Height="200" />
</BlockUIContainer>
</Paragraph>
</FlowDocument>
I am doubtful about textblock as well. That should probably be a run or paragraph.

I used the exact same code to test in .NetFramework 4.8 and in .NET6 respectively. It doesn't show pictures in .NetFramework 4.8 and shows pictures in .NET6(.NET5).
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="0" Grid.Column="1" HorizontalAlignment="Center" Width="80" Click="Button_Click_1">save as xps</Button>
<FlowDocumentReader Height="150" Width="170" Grid.Column="1" Grid.Row="1">
<FlowDocument Name="flowDocument" ColumnWidth="400" FontSize="14" FontFamily="Georgia">
<Paragraph>
<Grid>
<Image Source="C:\Users\Admin\Downloads\WpfApp3\45.jpg" Width="200" Height="300" />
<TextBlock Text="Hello World!" HorizontalAlignment="Center" VerticalAlignment="Top" Foreground="Red" />
</Grid>
</Paragraph>
</FlowDocument>
</FlowDocumentReader>
<Button Grid.Row="0" HorizontalAlignment="Center" Width="80" Click="Button_Click">open xps file</Button>
<DocumentViewer Name="viewer" Grid.Row="1"/>
Codebehind:
public static void SaveAsXps(string path, FlowDocument document)
{
using (var package = Package.Open(path, FileMode.Create))
{
using (var xpsDocument = new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum))
{
var xpsSerializationManager = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false);
var documentPaginator = ((IDocumentPaginatorSource)document).DocumentPaginator;
xpsSerializationManager.SaveAsXaml(documentPaginator);
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
{
string sFileName = #"C:\...\printPreview.xps";
XpsDocument doc = new XpsDocument(sFileName, System.IO.FileAccess.Read);
viewer.Document = doc.GetFixedDocumentSequence();
return;
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
SaveAsXps(#"C:\...\printPreview.xps", flowDocument);
}
The result in .NetFramework 4.8 :
The result in .NET6(.NET5) :

Related

how to properly use item click in gridview

I have a gridview, which presents all of the users I have in my database, and their details, I want to be able, on the click of a user(on the gridview), that it's details will appear separately on the side of the grid view, and there I could change them accordingly. However, I'm not sure how to do so. I have the ItemClick event in my gridview, and It does recognize if I click on an item, but I don't know how to get that specific clicked user's details, for me to present them on the side. I also have another problem- for some reason It doesn't recognize nor let me click on any of the top row items on the grid view-only the ones below it, does anyone know why?
this is my XAML :
<Page
x:Class="My_Little_Animal.ShowUsers"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:My_Little_Animal"
xmlns:data="using:My_Little_Animal"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/Assets/changeUserDetailesBackground.jpg"></ImageBrush>
</Grid.Background>
<Grid.RowDefinitions>
<RowDefinition Height="8*" />
<RowDefinition Height="147*"/>
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<GridView Name="grid1" ItemClick="grid1_ItemClick" IsItemClickEnabled="True" Margin="-70,151,692,50" Grid.RowSpan="2" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<GridView.ItemTemplate>
<DataTemplate x:DataType="data:User">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<StackPanel Margin="100,20,0,0">
<TextBlock Name="t1" FontSize="20" GotFocus="t1_GotFocus" Text="{x:Bind UserId}"/>
<TextBlock Name="t2" FontSize="20" GotFocus="t2_GotFocus" Text="{x:Bind Password}"/>
<TextBlock Name="t3" FontSize="20" GotFocus="t3_GotFocus" Text="{x:Bind UserName}"/>
<TextBlock Name="t4" FontSize="20" GotFocus="t4_GotFocus" Text="{x:Bind Email}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<Canvas>
<Image Name="loginTitle" Source="/Assets/ShowUsersTitle.png" RenderTransformOrigin="0.5,0.5" Grid.RowSpan="2" Canvas.Left="-325" Canvas.Top="-120" Height="462" Width="1875"/>
<TextBlock Grid.Row="2" Name="ResultTextBlock" FontSize="24" Foreground="Red" FontWeight="Bold" Height="169" Margin="0,0,0,-69"/>
<Image Name="editTheUserName" Width="100" Height="35" Visibility="Visible" Source="/Assets/editIcon.png" RenderTransformOrigin="0.5,0.5" Grid.Row="1" Canvas.Left="852" Canvas.Top="226" />
<Image Name="CancelTheUserNamE" Width="100" Height="35" Visibility="Visible" Source="/Assets/xIcon.png" RenderTransformOrigin="0.485,0.529" Grid.Row="1" Canvas.Left="848" Canvas.Top="224" />
<TextBlock Visibility="Visible" Name="theUserItself" FontFamily="Comic Sans MS" FontWeight="ExtraBold" FontStyle="Italic" FontSize="25" Text="your user name " RenderTransformOrigin="0.496,1.165" Foreground="#FF283D6C" Grid.Row="1" Canvas.Left="1103" Canvas.Top="219" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch"/>
<TextBlock Name="userName" FontFamily="Comic Sans MS" FontWeight="ExtraBold" FontStyle="Italic" FontSize="25" Text="User Name : " RenderTransformOrigin="0.496,1.165" TextDecorations="Underline" Grid.Row="1" Canvas.Left="922" Canvas.Top="224"/>
<TextBox Visibility="Visible" Width="200" Name="UserNameText" MaxLength="50" FontFamily="Comic Sans MS" FontStyle="Italic" FontSize="15" BorderThickness="3" BorderBrush="#FF23677D" Grid.Row="1" Canvas.Left="1099" Canvas.Top="223" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch"/>
<Button Visibility="Visible" Name="changeuserName" Height="49" Width="140" FontSize="20" Content="change" FontWeight="ExtraBold" BorderBrush="White" Foreground="White" BorderThickness="2" Background="#FF191A5C" HorizontalAlignment="Center" VerticalAlignment="Top" RenderTransformOrigin="0.45,0.536" Grid.Row="1" Canvas.Left="1305" Canvas.Top="210" Margin="0,0,0,0"/>
<Image Name="editTheEmail" Canvas.Top="286" Canvas.Left="850" Width="100" Height="35" Visibility="Visible" Source="/Assets/editIcon.png" RenderTransformOrigin="0.49,0.557" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
<Image Name="CancelTheEmail" Width="100" Height="35" Visibility="Visible" Source="/Assets/xIcon.png" RenderTransformOrigin="0.485,0.529" Grid.Row="1" Canvas.Left="847" Canvas.Top="284" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
<TextBlock Visibility="Visible" Name="theEmailItself" FontFamily="Comic Sans MS" FontWeight="ExtraBold" FontStyle="Italic" FontSize="25" Text="your email " RenderTransformOrigin="0.496,1.165" Foreground="#FF283D6C" Grid.Row="1" Canvas.Left="1105" Canvas.Top="276"/>
<TextBlock Name="Email" FontFamily="Comic Sans MS" FontWeight="ExtraBold" FontStyle="Italic" FontSize="25" Text="Email : " RenderTransformOrigin="0.496,1.165" TextDecorations="Underline" Grid.Row="1" Canvas.Left="921" Canvas.Top="283" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
<TextBox Visibility="Visible" Width="200" Name="EmailText" MaxLength="50" FontFamily="Comic Sans MS" FontStyle="Italic" FontSize="15" BorderThickness="3" BorderBrush="#FF23677D" Grid.Row="1" Canvas.Left="1093" Canvas.Top="284" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch"/>
<Button Visibility="Visible" Name="changeEmail" Height="49" Width="140" FontSize="20" Content="change" FontWeight="ExtraBold" BorderBrush="White" Foreground="White" BorderThickness="2" Background="#FF191A5C" HorizontalAlignment="Center" VerticalAlignment="Top" RenderTransformOrigin="0.45,0.536" Grid.Row="1" Canvas.Left="1302" Canvas.Top="274" Margin="0,0,0,0"/>
<Image Name="theReturn" Height="100" Width="100" Tapped="theReturn_Tapped_1" Source="/Assets/theReturnIcon.png" RenderTransformOrigin="0.493,0.496" Grid.RowSpan="2" Canvas.Left="65" Canvas.Top="27" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</Canvas>
</Grid>
The c# code :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Xml;
using System.Data;
using Windows.UI.Popups;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
namespace My_Little_Animal
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ShowUsers : Page
{
regitration.regitrationSoapClient cal;
public ShowUsers()
{
this.InitializeComponent();
cal = new regitration.regitrationSoapClient();
getData();
}
public async void getData()
{
regitration.getUserTableResponseGetUserTableResult r = await cal.getUserTableAsync();
List<User> theUserList = new List<User>();
User u = null;
XmlReader xr = r.Any1.CreateReader();
XmlDocument document = new XmlDocument();
document.Load(xr);
XmlNodeList theXmlList = document.GetElementsByTagName("Table");
foreach (XmlElement item in theXmlList)
{
u = new User();
foreach (XmlNode node in item.ChildNodes)
{
switch (node.Name)
{
case "userId": u.UserId = int.Parse(node.InnerText); break;
case "password": u.Password = node.InnerText; break;
case "userName": u.UserName = node.InnerText; break;
case "email": u.Email = node.InnerText; break;
}
}
theUserList.Add(u);
}
grid1.ItemsSource = theUserList;
}
private async void grid1_ItemClick(object sender, ItemClickEventArgs e)
{
var dialog = new MessageDialog("The item that was clicked is : ");
await dialog.ShowAsync();
}
private void t1_GotFocus(object sender, RoutedEventArgs e)
{
}
private void t2_GotFocus(object sender, RoutedEventArgs e)
{
}
private void t3_GotFocus(object sender, RoutedEventArgs e)
{
}
private void t4_GotFocus(object sender, RoutedEventArgs e)
{
}
private void theReturn_Tapped_1(object sender, TappedRoutedEventArgs e)
{
this.Frame.Navigate(typeof(Administrator));
}
}
}
I will be so thankful for any help, it's really important for me!
but I don't know how to get that specific clicked user's details, for me to present them on the side.
There are many ways to get the item in item click event. if you have used MVVM pattern, the recommend way is binding command. For more you could refer this case.
In general, you could subscribe ItemClick event and get ClickedItem from event ItemClickEventArgs
Example
private void VideoGridView_ItemClick(object sender, ItemClickEventArgs e)
{
var vedio = e.ClickedItem as VideoItem;
var item = new MediaPlaybackItem(MediaSource.CreateFromUri(new Uri(vedio.videoUri)));
mediaPlayerElement.Source = item;
}
I also have another problem- for some reason It doesn't recognize nor let me click on any of the top row items on the grid view-only the ones below it, does anyone know why?
I could not reproduce this issue, please check if there is some element cover the top row up cause the grid view could not be clicked.

reloading image in wpf window after changing the image

Recently I was working with WPF and C#, and I wanted to make an editor for an A4 page (A JPG template with the size of an A4)
The thing is, I want to put some text in a certain place on the JPG and to be able to see it as I write the text (like a live preview).
This is what I achieved by now:
XAML
<Window x:Class="Tut.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:Tut"
mc:Ignorable="d"
Title="Neshalet Logo ltd." Height="900" Width="1400">
<Border Padding="10">
<StackPanel Margin="0,10,0,0">
<Grid Height="839">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width=".3*"/>
</Grid.ColumnDefinitions>
<TextBlock Margin="0,2,22,817" HorizontalAlignment="Right" Grid.Column="2" FontSize="15">
בחר מוצר
</TextBlock>
<!-- Combo box for product type -->
<ComboBox x:Name="productType" Grid.Column="1" VerticalAlignment="Top" Height="25" Margin="10,0,17,0" >
<ComboBoxItem>באנרים</ComboBoxItem>
<ComboBoxItem>שקפים וניירות</ComboBoxItem>
<ComboBoxItem>וינילים</ComboBoxItem>
<ComboBoxItem>קשיחים הדפסה ישירה</ComboBoxItem>
<ComboBoxItem>הדבקה</ComboBoxItem>
</ComboBox>
<Image Source ="/Resources/a4.jpg" Grid.Column="0" Margin="10,35,0,0" HorizontalAlignment="Left" VerticalAlignment="Top">
</Image>
<!-- Main window -->
<StackPanel Grid.Column="1" Grid.ColumnSpan="2" Margin="10,40,0,0">
<Grid Height="492">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- SO Number-->
<TextBlock Grid.Column="1" FontSize="16" HorizontalAlignment="Right" Margin="0,5,22,472"><Run Text="מספר הזמנה"/></TextBlock>
<TextBox x:Name="SO" DataContextChanged="drawSO" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Top" Margin="0,0,5,0"/>
<!-- Costumer name -->
<TextBlock Grid.Column="1" FontSize="16" HorizontalAlignment="Right" Margin="0,34,22,440"><Run Text="שם לקוח"/></TextBlock>
<TextBox Grid.Column="0" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Top" Margin="0,30,5,0"/>
<!-- Order date -->
<TextBlock Grid.Column="1" FontSize="16" HorizontalAlignment="Right" Margin="0,64,22,410"><Run Text="תאריך"/></TextBlock>
<Button Grid.Column="1" Margin="9,62,122,410" Click="getDate" Content="היום" RenderTransformOrigin="0.5,0.5"/>
<DatePicker x:Name="todaysDate" Grid.Column="0" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Top" Margin="0,60,5,0"/>
<!-- Supply date -->
<TextBlock Grid.Column="1" FontSize="16" HorizontalAlignment="Right" Margin="0,93,22,381"><Run Text="תאריך אספקה"/></TextBlock>
<DatePicker x:Name ="deliveryDate" Margin="0,90,5,377" />
<!-- Folder -->
<TextBlock Grid.Column="1" FontSize="16" HorizontalAlignment="Right" Margin="0,123,22,351"><Run Text="נשמר בתיקיה"/></TextBlock>
<ComboBox x:Name="folderName" Grid.Column="0" Margin="0,120,5,347">
<ComboBoxItem Content="ktanot"/>
<ComboBoxItem Content="GZM"/>
<ComboBoxItem Content="UV"/>
<ComboBoxItem Content="SLAVA WATER PRINTS"/>
</ComboBox>
<!-- Folder -->
<TextBlock Grid.Column="1" FontSize="16" HorizontalAlignment="Right" Margin="0,154,22,320"><Run Text="קוד משלוח"/></TextBlock>
<ComboBox x:Name="DeliveryCode" Grid.Column="0" Margin="0,150,5,317">
<ComboBoxItem Content="איסוף עצמי"/>
<ComboBoxItem Content="מסירה"/>
<ComboBoxItem Content="משלוח"/>
</ComboBox>
<Button Margin="230,362,270,96" Click="Button_Click">
כאן
</Button>
</Grid>
</StackPanel>
<Label Content="תצוגה מקדימה" HorizontalAlignment="Center" VerticalAlignment="Top" Grid.Column="0"/>
</Grid>
<!-- Image preview -->
</StackPanel>
</Border>
C#
public partial class MainWindow : Window
{
public MainWindow() => InitializeComponent();
DateTime today = DateTime.Today.Date;
String path = #"/Resources/a4.jpg";
Bitmap order = null;
Font f = new Font("Arial", 200, GraphicsUnit.Pixel);
private void getDate(object sender, RoutedEventArgs e)
{
String t = today.ToShortDateString();
todaysDate.Text = t;
}
private void drawSO(object sender, DependencyPropertyChangedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
String orderNum = SO.Text;
using (var stream = File.OpenRead(path))
{
order = (Bitmap)Bitmap.FromStream(stream);
}
using (order)
using (var graphics = Graphics.FromImage(order))
using (f)
{
graphics.DrawString(orderNum, f, System.Drawing.Brushes.White, order.Height/2, order.Width/2);
order.Save(path);
}
}
}
The thing is that I made the program write the text only on a button click (as you can see on Button_Click(), but I want to to display the text I write on SO Number text box while I'm writing it.
Is there any way to refresh the image view on the window as I write the text and not on a Button click event?
Here is an example:
I want the text entered in the text box will be on the jpg
Just bind the Text property of the TextBlock to use the TextBox's Text.
Like so:
<TextBlock Grid.Column="1" FontSize="16" HorizontalAlignment="Right" Margin="0,5,22,472" Text="{Binding ElementName=SO, Path=Text, UpdateSourceTrigger=PropertyChanged}"/>
UPDATE
After the comments and the edited question.
You could place the TextBlock after the Image in a grid and then generate new image with all of the visuals included.
It would go something like this:
<Grid x:Name="imageToExport">
<Image Source ="/Resources/a4.jpg" Grid.Column="0" Margin="10,35,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Text="Some text here that will appear on top of the image"/><!-- The text property can use binding instead -->
</Grid>
Then you would save it as a jpeg, like this:
Image myImage = new Image();
FormattedText text = new FormattedText("ABC",
new CultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface(this.FontFamily, FontStyles.Normal, FontWeights.Normal, new
FontStretch()),
this.FontSize,
this.Foreground);
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawText(text, new Point(2, 2));
drawingContext.Close();
RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 120, 96,
PixelFormats.Pbgra32);
bmp.Render(drawingVisual);//In here you could just pass the name of the grid "imageToExport"
myImage.Source = bmp;
NOTE
Please note the code for saving the visual is from MSDN
The thing is that I made the program write the text only on a button click (as you can see on Button_Click(), but I want to to display the text I write on SO Number text box while I'm writing it. Is there any way to refresh the image view on the window as I write the text and not on a Button click event?
Try to handle the TextChanged event for the TextBox instead of handling the Click event for the Button:
<TextBox x:Name="SO" TextChanged="" ... />
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
String orderNum = SO.Text;
using (var stream = File.OpenRead(path))
{
order = (Bitmap)Bitmap.FromStream(stream);
}
using (order)
using (var graphics = Graphics.FromImage(order))
using (f)
{
graphics.DrawString(orderNum, f, System.Drawing.Brushes.White, order.Height / 2, order.Width / 2);
order.Save(path);
}
}
Note that the event handler will be invoked on each key press. If this is not desired for performance reasons, you might consider binding to a string property and implement some delay as suggested here.

How can I interact with a property in another frame? (C# / WPF)

I'm currently learning C# and WPF. Therefore I'm programming a little music player. But now I came to a problem. I was implementing different frames for menu items and other things I display.
Then my problem occoured. I have a MediaElement in my MainWindow.XAML(.CS) and I have to interact with that Element also in my Player.XAML(.CS) - Which obviously controls it (the Player can pause, play, stop, etc the MediaElement). The other class CurrentPlaylist.XAML(.CS) displays the current Playlist in a Datagrid. It shows information and can interact with the MediaElement (Setting a new Song / Start to play the song).
I really have no idea on how to achieve it when I have different Frames.
Here's a little bit of Code.
MainWindow.XAML
<Grid>
<MediaElement Name="media" HorizontalAlignment="Left" Width="1" Height="1" LoadedBehavior="Manual" UnloadedBehavior="Stop"
MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded"/>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Frame Width="1280" Height="100" Grid.ColumnSpan="2" Grid.Row="1" VerticalAlignment="Bottom" Source="Player.xaml"></Frame>
<StackPanel HorizontalAlignment="Left" Width="50" Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" Grid.ColumnSpan="2" Name="fullMenu" Background="{StaticResource flavorColor}" >
<Button Style="{StaticResource seeThrough}" Width="50" Height="70" x:Name="hamburgerMenu" Grid.Column="0" Grid.Row="0" BorderBrush="{x:Null}" Click="hamburger_Click" Cursor="Hand" HorizontalAlignment="Right">
<Rectangle Width="30" Height="30">
<Rectangle.Fill>
<DrawingBrush>
<DrawingBrush.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" />
<GeometryDrawing Brush="White" Geometry="F1M13,11L3,11 3,13 13,13z M13,7L3,7 3,9 13,9z M13,5L3,5 3,3 13,3z" />
</DrawingGroup.Children>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Rectangle.Fill>
</Rectangle>
</Button>
<Button Click="default_Playlist_Click" x:Name="item1" Style="{StaticResource seeThrough}" Content="{Binding CurrentPlaylist.Name}" Visibility="Collapsed"></Button>
<Button Click="playlist_List_Click" x:Name="item2" Style="{StaticResource seeThrough}" Content="Playlists" Visibility="Collapsed"></Button>
<Button Click="full_Player_Click" x:Name="item3" Style="{StaticResource seeThrough}" Content="MaxPlayer" Visibility="Collapsed"></Button>
</StackPanel>
</Grid>
Player.XAML
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition />
</Grid.RowDefinitions>
<Slider x:Name="timeLine" Grid.Column="0" VerticalAlignment="Center"/>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal" Grid.Column="1" Grid.Row="2">
<Button x:Name="previousSong" Width="75" Height="30" Margin="10,0,10,20">
<<
</Button>
<Button Click="PlayPause" x:Name="playSong" Width="75" Height="30" Margin="10,0,10,20">
||
</Button>
<Button x:Name="nextSong" Width="75" Height="30" Margin="10,0,10,20">
>>
</Button>
</StackPanel>
</Grid>
Player.XAML.cs
public partial class Player : Page
{
private TimeSpan TotalTime;
DispatcherTimer timer;
private bool playerRunning = false;
private MainWindow mw;
MediaElement Media;
public Player(MainWindow mw)
{
this.mw = mw;
Media = mw.Media;
InitializeComponent();
timeLine.AddHandler(MouseLeftButtonUpEvent,
new MouseButtonEventHandler(SeekMediaPosition),
true);
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(timer_Tick);
}
public void timer_Tick(object sender, EventArgs e)
{
timeLine.Value = timeLine.Value + 1000;
}
private void PlayPause(object sender, RoutedEventArgs e)
{
if (Media.Source != null && playerRunning == true)
{
Media.Pause();
playSong.Content = ">";
playerRunning = false;
}
else if (Media.Source != null && playerRunning == false)
{
Media.Play();
playSong.Content = "||";
playerRunning = true;
}
}
private void Element_MediaOpened(object sender, EventArgs e)
{
timeLine.Maximum = Media.NaturalDuration.TimeSpan.TotalMilliseconds;
TotalTime = Media.NaturalDuration.TimeSpan;
timer.Start();
}
private void Element_MediaEnded(object sender, EventArgs e)
{
Media.Stop();
}
private void SeekMediaPosition(object sender, MouseButtonEventArgs args)
{
int val = (int)timeLine.Value;
Media.Position = new TimeSpan(0, 0, 0, 0, val);
}
}
This was my latest idea. But well as I thought it won't work.
I would appreciate if you guys would give a little poke towards the answer. :)
I'm not entirely sure what you mean by frames, so that may be the problem. But, this worked for me.
' Configure open file dialog box
Dim dlg As New Microsoft.Win32.OpenFileDialog()
dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) & "iTunes\iTunes Media\Music"
dlg.FileName = "" ' Default file name
dlg.DefaultExt = ".txt" ' Default file extension
'dlg.Filter = "Music file (.mp3)|*.mp3;(.mp4)|*.mp4" ' Filter files by extension
dlg.Filter = "Music file (.mp3,.m4a)|*.mp3;*.m4a" ' Filter files by extension
' Show open file dialog box
Dim result? As Boolean = dlg.ShowDialog()
' Process open file dialog box results
If result = True Then
' Open document
Dim filename As String = dlg.FileName
Dim baseUri As New Uri(filename)
'MsgBox(filename)
myMediaElement.Stop()
myMediaElement.Source = baseUri
myMediaElement.Play()
End If
Also, I decided to stop using the media element all together because WMP (Actually, all Windows Media tech. I just uninstall it.) is nothing but a problem when you use it with iTunes. When I attempt my next one I will use a package that I found, easily find one in Tools -> Nuget Package Manager -> Manage NuGet Packages for Solution. Search for something like audio/music player.
The one I found, and was great for button beeps, was called NAudio.

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

Windows Phone App Crashes on ListPicker Selected Item

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();

Categories

Resources