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;
}
}
Related
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.
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.
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
}
My aim is to be able to add/ edit/delete items to a listbox. I have created a listbox of textboxes in the following way. I am able to display data but I am not able to edit data. Can someone help me modify the code so that I can achieve this functionality.
<ListBox Name="lbDemoBox" ItemsSource="{Binding testList}" Grid.Column="0" Grid.Row="0" SelectionChanged="lbDemoBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBox Text="{Binding Path=.}" KeyDown="TextBox_KeyDown" KeyUp="TextBox_KeyUp" GotFocus="TextBox_GotFocus"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Here is the code behind
public partial class MainPage : UserControl
{
private string focusedString { get; set; }
public MainPage()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
LayoutRoot.DataContext = new ViewModel();
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter && (Keyboard.Modifiers & (ModifierKeys.Shift)) == ModifierKeys.Shift)
{
(lbDemoBox.ItemsSource as ObservableCollection<string>).Add(string.Empty);
}
}
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
int index = (lbDemoBox.ItemsSource as ObservableCollection<string>).IndexOf(focusedString);
(lbDemoBox.ItemsSource as ObservableCollection<string>).RemoveAt(index);
}
}
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
focusedString = (sender as TextBox).Text;
}
private void lbDemoBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
public class ViewModel
{
public ObservableCollection<string> testList
{
get { return new ObservableCollection<string> { "Item1", "Item2", "Item3" }; }
}
}
Try this:
<TextBox Text="{Binding Path=YourProperty, Mode=TwoWay}" />
<Grid x:Name="LayoutRoot">
<TextBox x:Name="txt_diplay_1" HorizontalAlignment="Left" Height="42" Margin="155,78,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="103.5" GotFocus="txt_diplay_1_GotFocus" />
<TextBox x:Name="txt_diplay_2" Height="42" Margin="297,78,239.5,0" TextWrapping="Wrap" VerticalAlignment="Top" GotFocus="txt_diplay_2_GotFocus" />
<Button x:Name="btn_a" Content="A" HorizontalAlignment="Left" Height="40" Margin="155,147,0,0" VerticalAlignment="Top" Width="73" Click="btn_a_Click" />
<Button x:Name="btn_b" Content="B" Height="40" Margin="237,147,0,0" VerticalAlignment="Top" Click="btn_b_Click" HorizontalAlignment="Left" Width="73" />
<Button x:Name="btn_c" Height="40" Margin="0,147,239.5,0" VerticalAlignment="Top" HorizontalAlignment="Right" Width="73" Click="btn_c_Click" >
<Grid Height="30.833" Width="61.5">
<Label x:Name="lbl_1" Content="1" Margin="22.498,6.5,19.501,2.166"/>
<Label x:Name="lbl_2" Content="!" HorizontalAlignment="Right" Margin="0,-4.422,0,13.088" Width="19.501"/>
</Grid>
</Button>
</Grid>
The design will be like this
public partial class MainWindow : Window
{
Control TexboxDetails = null;
Control ButtonDetails;
Button BehaveButton;
public MainWindow()
{
this.InitializeComponent();
}
private void btn_a_Click(object sender, RoutedEventArgs e)
{
ButtonDetails = (Control)sender;
all_in_one();
}
private void btn_b_Click(object sender, RoutedEventArgs e)
{
ButtonDetails = (Control)sender;
all_in_one();
}
private void btn_c_Click(object sender, RoutedEventArgs e)
{
}
private void txt_diplay_1_GotFocus(object sender, RoutedEventArgs e)
{
TexboxDetails = (Control)sender;
}
private void txt_diplay_2_GotFocus(object sender, RoutedEventArgs e)
{
TexboxDetails = (Control)sender;
}
public void all_in_one()
{
BehaveButton = ButtonDetails as Button;
if (TexboxDetails != null)
{
TextBox BehaveTextbox = TexboxDetails as TextBox;
var caret_index = BehaveTextbox.CaretIndex;
BehaveTextbox.Text = BehaveTextbox.Text.Insert(caret_index, BehaveButton.Content.ToString());
BehaveTextbox.Focus();
BehaveTextbox.CaretIndex = caret_index + 1;
}
}
}
With above code i can get Button name dynamically when i click that button.
In above figure one button(btn_c) has two labels. now i want get that separate labels name dynamcially when i click button(btn_c).
You can get them like this (inside the btn_c click handler):
var btn_c = (Button)sender;
Grid grid = (Grid)btn_c.Content;
Label label1 = (Label)grid.Children[0];
string name1 = label1.Name;
Your whole design could really use some rework. Take a look at this code: (notice the reduced number of event handlers; you'll need to modify the XAML to use these)
public partial class MainWindow : Window
{
TextBox LastFocusedTextBox;
public MainWindow()
{
this.InitializeComponent();
}
private void btn_Click(object sender, RoutedEventArgs e)
{
InsertButtonContent((Button)sender);
}
private void txt_diplay_GotFocus(object sender, RoutedEventArgs e)
{
LastFocusedTextBox = (TextBox)sender;
}
public void InsertButtonContent(Button button)
{
if (LastFocusedTextBox != null)
{
string buttonContentString = button.Content as string;
if (string.IsNullOrEmpty(buttonContentString))
{
var grid = button.Content as Grid;
if (grid != null)
buttonContentString = string.Join("", grid.Children.OfType<ContentControl>().Select(x => x.Content));
}
var caret_index = LastFocusedTextBox.CaretIndex;
LastFocusedTextBox.Text = LastFocusedTextBox.Text.Insert(caret_index, buttonContentString);
LastFocusedTextBox.Focus();
LastFocusedTextBox.CaretIndex = caret_index + buttonContentString.Length;
}
}
}
Notice how the Button are passed to the method instead of being stored in a field. Also, unnecessary fields, both in the class and local to the all_in_one() method were removed. To get the contents of the labels in the Grid (e.g. "1!" - I assume this is what you were after, since nothing else could go into a simple string field, and also match the general pattern of your first two buttons), we simply select their contents and join them into a single string, after checking if the content was a string or a Grid.