how to have a slideshow of images in windows phone application development - c#

I am building my first app for windows phone application with visual C# 2010.
I want to have a slideshow of images in a page
In that slideshow when the image is clicked i want to navigate to another page.
I googled it but didnt get much help. What i tried is:
void Page1_Loaded(object sender, RoutedEventArgs e)
{
LoadImages();
}
private void LoadImages()
{
Image.Add("Image/aaa.jpg");
Image.Add("Image/bbb.jpg");
Image.Add("Image/ccc.jpg");
Image.Add("Image/ddd.jpg");
}
I wrote these code in the design page of the page where i need the slideshow of images.

Check this sample.
Add an Image in MainPage.xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Image x:Name="Img" Height="400" Tap="Img_OnTap" ></Image>
</Grid>
Do the following in MainPage.xaml.cs
private List<string> _images;
/// <summary>
/// List of images
/// </summary>
public List<string> Images
{
get { return _images; }
set { _images = value; }
}
//selected image index
public int SelectedImageIndex { get; set; }
// Constructor
public MainPage()
{
InitializeComponent();
this.Loaded += MainPage_Loaded;
this.DataContext = this;
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
LoadImages();
DispatcherTimer t = new DispatcherTimer();
//setting a 5 second interval
t.Interval = new TimeSpan(0, 0, 5);
t.Tick += t_Tick;
t.Start();
}
void t_Tick(object sender, EventArgs e)
{
if (SelectedImageIndex == Images.Count-1)
SelectedImageIndex = 0;
else
SelectedImageIndex++;
SetImageSource(Images[SelectedImageIndex]);
}
//Populating image list
private void LoadImages()
{
if (Images == null)
Images = new List<string>();
Images.Add("/Image/aaa.jpg");
Images.Add("/Image/bbb.jpg");
Images.Add("/Image/ccc.jpg");
Images.Add("/Image/ddd.jpg");
SelectedImageIndex = 0;
SetImageSource(Images[SelectedImageIndex]);
}
//setting image source
private void SetImageSource(string imagePath)
{
Img.Source = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));
}
//Image tap event
private void Img_OnTap(object sender, GestureEventArgs e)
{
string selectedImagePath = Images[SelectedImageIndex];
//Put your navigation here
}

You can create your own slide show with timer and a listbox control try this
Your xaml Code should be
<ListBox Grid.Row="1" Name="listControlImage" SelectionChanged="listControlImage_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Image Height="600" Width="460" Stretch="Fill" Source="{Binding}"/>
</ListBox.ItemTemplate>
</DataTemplate>
your code behind code should be
//global variables
List<BitmapImage> ListImages = new List<BitmapImage>();
DispatcherTimer Timer = new DispatcherTimer();
int SlideCount=0;
void Page1_Loaded(object sender, RoutedEventArgs e)
{
LoadImages();
DisTimer.Tick += DisTimer_Tick;
DisTimer.Interval = new TimeSpan(0, 0, 1);
DisTimer.Start();
}
private void LoadImages()
{
ListImages.Add( new BitmapImage(new Uri("/Your project name;component/Image/aaa.jpg", UriKind.Relative)));
ListImages.Add( new BitmapImage(new Uri("/Your project name;component/Image/bbb.jpg", UriKind.Relative)));
ListImages.Add( new BitmapImage(new Uri("/Your project name;component/Image/ccc.jpg", UriKind.Relative)));
ListImages.Add( new BitmapImage(new Uri("/Your project name;component/Image/ddd.jpg", UriKind.Relative)));
ListImages.ItemsSource =ListImages;
}
void DisTimer_Tick(object sender, EventArgs e)
{
if(SlideCount<=3)
{
listControlImage.SelectedIndex = SlideCount;
SlideCount++;
}
else
SlideCount=0;
}
private void listControlImage_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
if(listControlImage.SelectedIndex ==-1)
return;
//Your Navigation code
}

Related

.NET Maui Label text does not change its value

I am having issue that I've been struggling since I was programming apps in Xamarin. The problem is when I want change a label's text value outside from the ContentPage's Main method it does not update on the user interface.
public partial class MainPage : ContentPage
{
int command = 0;
SimpleTcpServer server1 = null;
SimpleTcpServer server2 = null;
System.Timers.Timer timer = null;
string iPPort = null;
public string Data { get; set; } = "getting data";
public MainPage()
{
InitializeComponent();
NetworkAccess accessType = Connectivity.Current.NetworkAccess;
if (accessType == NetworkAccess.Internet)
{
server1 = new SimpleTcpServer("10.0.0.9:10000");
server2 = new SimpleTcpServer("10.0.0.9:11000");
timer = new System.Timers.Timer(150);
timer.Elapsed += Tick;
timer.AutoReset = true;
server1.Events.ClientConnected += ClientConnected;
server1.Events.ClientDisconnected += ClientDisconnected;
server2.Events.ClientConnected += ClientConnected2;
server2.Events.ClientDisconnected += ClientDisconnected2;
server2.Events.DataReceived += DataReceived2;
label.Text = Data;
server1.Start();
server2.Start();
}
}
public void DataReceived2(object sender, SuperSimpleTcp.DataReceivedEventArgs e)
{
ArraySegment<byte> buffer = e.Data;
Data = Encoding.Default.GetString(buffer);
label.Text = Data;
}
private void ClientDisconnected2(object sender, ConnectionEventArgs e)
{
throw new NotImplementedException();
}
private void ClientConnected2(object sender, ConnectionEventArgs e)
{
}
private void Tick(object sender, ElapsedEventArgs e)
{
server1.Send(iPPort, command.ToString());
}
private void ClientDisconnected(object sender, ConnectionEventArgs e)
{
throw new NotImplementedException();
}
private void ClientConnected(object sender, ConnectionEventArgs e)
{
iPPort = e.IpPort;
timer.Start();
}
private void Forward(object sender, EventArgs e)
{
command = 1;
}
private void Backward(object sender, EventArgs e)
{
command = 2;
}
private void Left(object sender, EventArgs e)
{
command = 3;
}
private void Right(object sender, EventArgs e)
{
command = 4;
}
private void Released(object sender, EventArgs e)
{
command = 0;
}
}
This is my .NET Maui C# program which basically creates two Tcp listeners, which listen to two ports-one for sending and one for receiving (It is important to be on two different ports because of the second part of the project). When a data is received from the second port (the receiving port) a method DataReceived2 is raised and it gets the data and changes the label text value with it. When I debug the program I see that the value of label is changed with what it should be but it does not change on the ContentPage. I tried Data biding too, but the result is the same.
<StackLayout>
<Grid x:Name="grid">
<StackLayout VerticalOptions="CenterAndExpand" Margin="10,290,0,0">
<StackLayout Orientation="Horizontal">
<StackLayout Margin="0,120,0,60">
<Button VerticalOptions="CenterAndExpand" BackgroundColor="Green" Pressed="Forward" Released="Released" CornerRadius="50" Margin="0,0,0,-20" HeightRequest="100" WidthRequest="100"></Button>
<Button HeightRequest="100" Pressed="Backward" BackgroundColor="Green" Released="Released" WidthRequest="100" CornerRadius="50"></Button>
</StackLayout>
<StackLayout Margin="20,200,0,120" Orientation="Horizontal">
<Button CornerRadius="100" Pressed="Left" BackgroundColor="Green" Released="Released" HeightRequest="100" WidthRequest="100"></Button>
<Button HeightRequest="100" Pressed="Right" BackgroundColor="Green" Released="Released" Margin="10,0,0,0" WidthRequest="100" CornerRadius="60"></Button>
</StackLayout>
</StackLayout>
</StackLayout>
<StackLayout x:Name="stack">
<Label x:Name="label" Text="" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
</StackLayout>
</Grid>
</StackLayout>
And this is my xaml code.Can somebody help with this problem.
Thanks #Oliver, working for me:
in MAUI showing a progress label-text in webClient.DownloadAsync() like this:
XAML
<Label x:Name="progressBarText"
Text="..." />
C#
private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
try
{
progressBar.Progress = (double)(e.ProgressPercentage / 100.0);
Application.Current.MainPage.Dispatcher.Dispatch(() => progressBarText.Text = String.Format( "Downloading {0}%", e.ProgressPercentage ));
}
catch (Exception error)
{
throw error;
}
}

Use a webservice to get a random video and play it. C# WPF

I need help figuring out where to start on using a webservice to get a random video to play. This is the program instructions I am working on:
For this problem, you will be using a webservice to get a random video to play. The webservice can be found at : http://pcbstuou.w27.wh-2.com/webservices/3033/api/random/video . You will want to have a button to get a random video from the webservice for the user to press as well as a play and stop button. When the video is playing, the play button should double as a pause button and should change the text to reflect the available option.
This is what I have:
namespace Problem3
{
public partial class Media
{
private bool mediaPlayerIsPlaying = false;
public mePlayer;
private void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void Open_Executed(object sender, ExecutedRoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Media files (*.mp3;*.mpg;*.mpeg)|*.mp3;*.mpg;*.mpeg|All files (*.*)|*.*";
if (openFileDialog.ShowDialog() == true)
mePlayer.Source = new Uri(openFileDialog.FileName);
}
private void Play_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = (mePlayer != null) && (mePlayer.Source != null);
}
private void Play_Executed(object sender, ExecutedRoutedEventArgs e)
{
mePlayer.Play();
mediaPlayerIsPlaying = true;
}
private void Stop_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = mediaPlayerIsPlaying;
}
private void Stop_Executed(object sender, ExecutedRoutedEventArgs e)
{
mePlayer.Stop();
mediaPlayerIsPlaying = false;
}
The meplayer is having an error and I obviously need to create a method for it, but what would the method include? Also, I am not sure if I even went about this right?
This is the Main:
namespace Problem3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Search_button_Click(object sender, RoutedEventArgs e, object mediaElement)
{
//var FullVimeoUrl = "http://pcbstuou.w27.wh-2.com/webservices/3033/api/random/video ";
//mediaElement.Source = new Uri(FullVimeoUrl.ToString(), UriKind.RelativeOrAbsolute);
//mediaElement.Play();
}
private void Search_button_Click(object sender, RoutedEventArgs e)
{
var FullVimeoUrl = "http://pcbstuou.w27.wh-2.com/webservices/3033/api/random/video ";
mediaElement.Source = new Uri(FullVimeoUrl.ToString(), UriKind.RelativeOrAbsolute);
mediaElement.Play();
}
public void VideoPath(object sender, RoutedEventArgs e)
{
}
private class mediaElement
{
public static Uri Source { get; internal set; }
}
//public string Play()
//{
//}
private void Play_Click(object sender, RoutedEventArgs e)
{
//void OnMouseDownPauseMedia(object sender, MouseButtonEventArgs args)
//{
// // The Pause method pauses the media if it is currently running.
// // The Play method can be used to resume.
// mediaElement.Pause();
//}
}
private void Stop_Click(object sender, RoutedEventArgs e)
{
}
}
I am sure I have myself all mixed up because I have been working on this entirely too long. I am at the point of way overthinking!
Please try this code, To Use a webservice to get a random video and play it. C# WPF
XAML file:
<Window x:Class="WpfTutorialSamples.Audio_and_Video.MediaPlayerVideoControlSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MediaPlayerVideoControlSample" Height="300" Width="300">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<MediaElement Source="http://hubblesource.stsci.edu/sources/video/clips/details/images/hst_1.mpg" LoadedBehavior="Manual" Name="mePlayer" />
<StackPanel Grid.Row="1">
<Label Name="lblStatus" Content="Not playing..." HorizontalContentAlignment="Center" Margin="5" />
<WrapPanel HorizontalAlignment="Center">
<Button Name="btnPlay" Click="btnPlay_Click">Play</Button>
<Button Name="btnPause" Margin="5,0" Click="btnPause_Click">Pause</Button>
<Button Name="btnStop" Click="btnStop_Click">Stop</Button>
</WrapPanel>
</StackPanel>
</Grid>
</Window>
Class File:
using System;
using System.Windows;
using System.Windows.Threading;
namespace WpfTutorialSamples.Audio_and_Video
{
public partial class MediaPlayerVideoControlSample : Window
{
public MediaPlayerVideoControlSample()
{
InitializeComponent();
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
if(mePlayer.Source != null)
{
if(mePlayer.NaturalDuration.HasTimeSpan)
lblStatus.Content = String.Format("{0} / {1}", mePlayer.Position.ToString(#"mm\:ss"), mePlayer.NaturalDuration.TimeSpan.ToString(#"mm\:ss"));
}
else
lblStatus.Content = "No file selected...";
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
mePlayer.Play();
}
private void btnPause_Click(object sender, RoutedEventArgs e)
{
mePlayer.Pause();
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
mePlayer.Stop();
}
}
}
I hope this code will be useful for you.
Thank you.

button will be Visible if another window loaded

i have project where i want button in the MainWindow to be Visible if another window is loaded and Collapsed if this window is close
i have try in this way
Xaml for MainWindow
<Grid >
<Button x:Name="button" Content="Opne Window1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="button_Click" Margin="220,110,0,0"/>
<Button x:Name="WinBut1" Content="Check order" HorizontalAlignment="Left" VerticalAlignment="Top" Visibility="Hidden" Width="75" Click="button9_Click" Margin="10,1,0,0"/>
</Grid>
in the codebehind of the MainWindow control:
public partial class MainWindow : Window
{
Window1 Window1 = new Window1();
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
//this.Window1.Loaded += new RoutedEventHandler (CheckWindow);
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Window1 childWindow = new Window1();
childWindow.MyEvent += new EventHandler(childWindow_MyEvent);
childWindow.ShowDialog();
}
void childWindow_MyEvent(object sender, EventArgs e)
{
if (Window1 != null)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(
delegate ()
{
WinBut1.Visibility = Visibility.Visible;
}
));
}
}
//void CheckWindow(object sender, RoutedEventArgs e)
//{
// if (Window1 != null && Window1.Visibility == Visibility.Visible)
// {
// Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(
// delegate ()
// {
// WinBut1.Visibility = Visibility.Visible;
// }
// ));
// }
//}
private void button_Click(object sender, RoutedEventArgs e)
{
new Window1().Show();
}
}
in the codebehind of the Window1 control:
public Window1()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(win1_Loaded);
}
public event EventHandler MyEvent;
protected void OnMyEvent()
{
if (this.MyEvent != null)
this.MyEvent(this, EventArgs.Empty);
}
void win1_Loaded(object sender, RoutedEventArgs e)
{
this.OnMyEvent();
}
}
Well , there are tow events Loaded and Closed in Window class object.
You need to subscribe two events handler to them. All is done in your Window class.
Well based on your requirment you can do the following:
private void Button_Click(object sender, RoutedEventArgs e)
{
Window1 win = new Window1();
win.Loaded += win_Loaded;
win.Closed += win_Closed;
win.ShowDialog();
}
void win_Closed(object sender, EventArgs e)
{
this.but.Visibility = Visibility.Visible;
}
void win_Loaded(object sender, RoutedEventArgs e)
{
this.but.Visibility = Visibility.Hidden;
}
Well this code is used in your window code behind.
It's quite simple you only need to the IsVisibleChanged of Window1 in your MainWindow and set visibility of your button to the visibility of your window1.
Your MainWindow.cs:
public partial class MainWindow : Window
{
Window1 window1;
public MainWindow()
{
InitializeComponent();
window1 = new Window1();
window1.IsVisibleChanged += Window1_IsVisibleChanged;
this.Closing += MainWindow_Closing;
}
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Application.Current.Shutdown();//will close all windows
}
private void Window1_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
buttonCollapsed.Visibility = window1.Visibility;
}
private void buttonShow_Click(object sender, RoutedEventArgs e)
{
window1.Show();
}
And Window1.cs:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.Closing += Window1_Closing;
}
private void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if(sender is Window1)
{
e.Cancel = true;//Cancel the closing
this.Hide();
}
}
private void buttonHide_Click(object sender, RoutedEventArgs e)
{
this.Hide();//hide your window --> IsVisibilityChanged-Event will be raised
}
}

Isolated storage in In a multi-page c#

I have created two pages in the application ...
There on the front page Tkstpeix write your name when entering the storage and set up the application on this page,
And when you enter the second page in the application name does not come out!
Example:
When I open the app and type in my name "Ibra" the text box on the second page my name does not appear!
->Page1:
using myProject.Model;
public partial class Test1 : PhoneApplicationPage
{
IsolatedStorageSettings Data = IsolatedStorageSettings.ApplicationSettings;
List<UserData> ObjUserDataList = new List<UserData>();
public Test1()
{
InitializeComponent();
this.Loaded += Test1_Loaded;
}
private void Test1_Loaded(object sender, RoutedEventArgs e)
{
if (Data.Contains("UserNameData"))
{
NavigationService.Navigate(new Uri("/Test2.xaml", UriKind.Relative));
}
}
private void NameBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox tb = (TextBox)sender;
tb.BorderBrush = new SolidColorBrush(Colors.LightGray);
}
private void button_Click(object sender, RoutedEventArgs e)
{
Data["UserNameData"] = NameBox.Text;
NavigationService.Navigate(new Uri("/Test2.xaml", UriKind.Relative));
}
}
-->Page2:
using myProject.Model;
public partial class Test2 : PhoneApplicationPage
{
IsolatedStorageSettings Data = IsolatedStorageSettings.ApplicationSettings;
UserData ObjUserData = new UserData();
public Test2()
{
InitializeComponent();
this.Loaded += Test2_Loaded;
}
private void Test2_Loaded(object sender, RoutedEventArgs e)
{
if (Data.Contains("UserNameData"))
{
StckUserDetailsUI.DataContext = ObjUserData;
}
}
}
<StackPanel Name="StckUserDetailsUI" Grid.Row="0" Margin="12,17,0,28" Grid.ColumnSpan="2">
<TextBlock Text="Your Details :" Foreground="White" FontSize="30" TextDecorations="Underline"/>
<TextBlock FontSize="40" Name="TxtUserName" Text="{Binding UserName}" Foreground="White"/>
</StackPanel>
--->UserData.Cs: (in in the file /Model)
class UserData
{
public string UserName { get; set; }
}
note:
I work in windows phone 8.1 silverlight
You set the DataContext to ObjUserData but you never put anything for ObjUserData.UserName, hence it comes back as blank.

Image not displaying XAML

I created my own button that has Icon on the side and text on the other but the problem is the image is not displaying. did i miss something here? any help would be appreciated. TIA
This is the XAML of the control.
<UserControl x:Name="QButtonControl"
x:Class="CommonLayout.QButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CommonLayout"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="36"
d:DesignWidth="145" MinWidth="145" MinHeight="36" Loaded="QButtonControl_Loaded">
<Grid PointerEntered="Grid_PointerEntered_1" PointerExited="Grid_PointerExited_1" MinWidth="145" MinHeight="36" Background="#FFDCD1D1">
<TextBlock x:Name="btnLabel" Height="20" Margin="36,8,4,8" TextWrapping="Wrap" Text="Text Here" VerticalAlignment="Center" FontSize="18.667" Width="105"/>
<Image x:Name="img" HorizontalAlignment="Left" Height="27" Margin="1,4,0,0" VerticalAlignment="Top" Width="29"/>
</Grid>
</UserControl>
This is code behind the control.
public sealed partial class QButton : UserControl
{
private ImageSource iconDefault;
private Brush hoverBrush = new SolidColorBrush(Color.FromArgb(255, 228, 228, 228));
public string Text
{
get
{
return btnLabel.Text;
}
set
{
btnLabel.Text = value;
}
}
public ImageSource Icon
{
get
{
return iconDefault;
}
set
{
iconDefault = value;
img.Source = value;
}
}
public Brush HoverBrush
{
get
{
return hoverBrush;
}
set
{
hoverBrush = value;
}
}
public QButton()
{
this.InitializeComponent();
}
private void Grid_PointerEntered_1(object sender, PointerRoutedEventArgs e)
{
btnLabel.Foreground = HoverBrush;
}
private void Grid_PointerExited_1(object sender, PointerRoutedEventArgs e)
{
btnLabel.Foreground = Foreground;
}
private void QButtonControl_Loaded(object sender, RoutedEventArgs e)
{
img.Source = iconDefault;
}
}
First of all, do not use a hard coded file path to the image.
Windows Store apps run in a sandbox, so you will not be able to get to any arbitrary file location when you deploy your app.
Second, you can't use backslashes in Image URI. The backslashes are the technical reason you are setting the error you are getting. But just changing to forward slashes in not the answer.
Access Image in XAML
If you add an image to your projects /Assets folder, you can use XAML like this to show it in QButton.
<local:QButton x:Name='qButton1'
Icon='/assets/jellyfish.jpg' />
In Code
To change the Icon in code.
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/shrimp.jpg"));
var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var image = new BitmapImage();
image.SetSource(fileStream);
qButton1.Icon = image;
}
If you want the user to choose the Image from their computer at runtime, look at the File Pickers.
MSDN file pickers
Are you forgetting to set the Icon property?
This worked for me
<local:QButton Icon="C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg" />
This worked as well
public QButton()
{
this.InitializeComponent();
Uri imageUri = new Uri(#"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg");
BitmapImage image = new BitmapImage(imageUri);
this.Icon = image;
}

Categories

Resources