Print transient text in a textBlock: WP8 and dispatcher magic - c#

I am new to Windows Phone development and I am trying to do something which I believe is quite simple: I have a page, with a button and a textBlock. I would like that, whenever the button is pressed, the textBlock's text change to "Bazinga!" for a few seconds and then revert to its previous value.
I have tried the code below but it does not work (I suppose because the textBlock's display is not refreshed while still in the Button_Click call).
After looking up a few keywords, I saw this: WPF not updating textbox while in progress
This tells me I must explicitly call the Dispatcher's Invoke method... but I only see a BeginInvoke() method (I guess this is a specificity of Windows Phone) and my few attempts at getting it right have been unlucky.
Thanks for any help you can
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Function();
}
private void Function()
{
string text = this.TextBlock1.Text;
DateTime until = DateTime.Now.AddSeconds(5.0);
this.TextBlock1.Text = "Bazinga!";
while (DateTime.Now < until)
{
// Do nothing
}
this.TextBlock1.Text = text;
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
string text = TextBlock1.Text;
TextBlock1.Text = "Bazinga!";
await Task.Delay(5000);
TextBlock1.Text = text;
}

Related

Program for learning foreign words C#

I am in the process of writing a vocabulary program. C # Windows Form.
Description of the program operation:
Use the buttons to select the location of text files with the words "PL" and "ENG". (two separate files)
Click the start button to start the program
the first word from the board appears in the label
I'm translating the word into the textbox and the Messagebox "OK" or "WRONG" pops up
And here a problem arises. The program instead of every time I wait until I introduce a new word to the textbox, it loops, the questions in the label are changed and MessageBox displays.
How best to do this to make the program work correctly? `` `[
private void sprawdzButton_Click(object sender, EventArgs e)
{
BazaSlow.bazaPolskichSlowek = _fileReader.Read(adresPlikuPL);
BazaSlow.bazaAngielskichSlowek = _fileReader.Read(adresPlikuANG);
string odpowiedz = odpTextBox.Text;
int i = 0;
while (i < BazaSlow.bazaPolskichSlowek.Length)
{
trescSlowkaLabel.Text = BazaSlow.bazaPolskichSlowek[i];
if (odpowiedz.Equals(BazaSlow.bazaAngielskichSlowek[i].ToLower()))
{
MessageBox.Show("OK");
}
else
{
MessageBox.Show("ŹLE");
}
i++;
}
}
This approach will not quite work.
If you use WinForms then you can do it via events. I'll quickly use english variable names since I don't speak your language.
This could be one approach to do it: I used the "TextChanged" event from the textBox.
string[] wordsLanguage1;
string[] wordsLanguage2;
int currentIndex = 0;
private void Form1_Load(object sender, EventArgs e)
{
wordsLanguage1 = System.IO.File.ReadAllLines("somePath1");
wordsLanguage2 = System.IO.File.ReadAllLines("somePath2");
}
private void ReportAndCheckInput(string input)
{
if (input.ToLower().Equals(wordsLanguage2[currentIndex].ToLower())) {
//right translation
currentIndex++;
label1.Text = wordsLanguage1[currentIndex];
textBox1.Text = "";
}
else
{
//wrong translation
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
ReportAndCheckInput(textBox1.Text);
}
Now this approach uses the TextChanged event. So the ReportAndCheckInput method will be called on every text-change. That means that your Feedback would pop up on every keystroke which would not be nice. You could use any other event instead of TextChanged. For example a button click. Another solution would be to use a label for your feedback and not a message box. Then the user would never have to click anything but woudl instantly see whether or not he was correct.

System.FormatException occurred in mscorlib.dll when converting it int32

I know, i know there are lots and lots of questions asking on here about this error, each with their own response, but its easier to work off a response regarding your own code rather than someone else's
I have been working on this program for some time for a college assignment, and as soon as i started putting in the class to calculate the totals of things it now crashes,
I don't know where to look so i'll post my main code
enter code here
namespace Till
public partial class MainWindow : Window
{
Calculator calc = new Calculator();
public MainWindow()
{
InitializeComponent();
}
public bool User;
public bool tillopen = false;
private void button_Click(object sender, RoutedEventArgs e)
{
//button clone thingy
Button btn = (Button)sender;
label.Content = label.Content + btn.Content.ToString();
Console.Beep(); // makes the buttons beep
}
private void clear_Click(object sender, RoutedEventArgs e)
{
// Clear
label.Content = "";
}
private void Button_Submit_Click(object sender, RoutedEventArgs e)
{
// submit
listView.Items.Add(label.Content);
label.Content = "";
calc.setSoldItems(Convert.ToInt32(label.Content)); /// it breaks on this line///
}
private void button13_Click(object sender, RoutedEventArgs e)
{
//void sale
label.Content = "";
listView.Items.Clear();
}
private void button15_Click(object sender, RoutedEventArgs e)
{
//pound
label.Content = "1.00";
}
private void button12_Click(object sender, RoutedEventArgs e)
{
//till open close
tillopen = true;
}
private void button16_Click(object sender, RoutedEventArgs e)
{
Login m = new Login();
m.Show();
this.Close();
}
private void button14_Click(object sender, RoutedEventArgs e)
{
label.Content = "2.00"; // 2 pound
}
private void button17_Click(object sender, RoutedEventArgs e)
{
label.Content = calc.finish();
}
}
I have tried to re-create the error in another WPF (converting a to an int32) and it works fine, i know this is an issue with my code itself, i have tried using other machine and using different versions of visual studio itself, so we came to the assumption its this code itself and not a broken dll file
So before I sit down with my Teacher and spend all day going though my code step by step im asking around for help in order to save both of our time, This assignment is due in in 3 weeks, and it decides to break on me now.
thankies
To replicate this error, i press a number button on my Windows form, them hit the submit button i created (which starts the conversion) If a copy of my class which handles all of this is needed im happy to post it
In the method button_click, you have assigned value as
label.Content = label.Content + btn.Content.ToString();
which is a string value to the label and the values are concatenated instead of add.
and when you are reading it, you are converting it in Int32. which will give exception as it will not contain any integer value to it.
You can add the value like this:
label.Content = (Convert.ToInt32(label.Content) + Convert.ToInt32(btn.Content)).ToString();
and check before converting if the label has blank values in it, if it has do not convert them, and only convert the value if it has some values it will not give any error. Also do not assign any values other that numerical digits.
You are calculating:
Convert.ToInt32(label.Content)
but on the line before you set:
label.Content = "";
so this means you are calculating
Convert.ToInt32("")
which gives you a FormatException.
Perhaps you should use the value of label.Content before you overwrite it?

c# Taskbar Progress Bar, getting value from Windows Media Player currentMedia.currentPosition

What I tried to was getting the value in the following way, which didn't work:
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal);
axWindowsMediaPlayer1.Ctlcontrols.play();
axWindowsMediaPlayer1.Ctlcontrols.currentItem =
axWindowsMediaPlayer1.currentPlaylist.Item[listBox1.SelectedIndex];
backgroundWorker2.RunWorkerAsync();
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
double val = 100*axWindowsMediaPlayer1.Ctlcontrols.currentPosition/axWindowsMediaPlayer1.currentMedia.duration;
TaskbarManager.Instance.SetProgressValue((int)val,100);
}
I am also not sure, where would I put the line for stopping the progress, but I guess it is a bit early to think about it, since I can't get the progress to work anyway.
Is the problem in how I used the backgroundWorker or in how I update the value, or something else?
Thanks in advance,
~~hlfrmn
EDIT:
private void TaskbarProgressValueDeterminator()
{
TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal);
while (axWindowsMediaPlayer1.Ctlcontrols.currentPosition < axWindowsMediaPlayer1.currentMedia.duration)
{
TaskbarManager.Instance.SetProgressValue((int)(100 * axWindowsMediaPlayer1.Ctlcontrols.currentPosition / axWindowsMediaPlayer1.currentMedia.duration), 100);
}
TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress);
}
The background worker will update the progress only once. I expect you need to put in a while loop or a timer to update the progress repeatedly while the track is playing.

StatusLabel - how to reset, or allow status text to time out or fade away

I have a tabbed form with a StatusStrip at the bottom, which includes a StatusLabel. I want to use this status label for various actions ("1 record updated" etc). It is simple enough to create specific events to set the label's text property.
But how best to reset the status to blank? The user could perform any number of other operations where the status is no longer meaningful (going to another tab, clicking other buttons etc.).
It is not feasible to create all the possible events to reset the status message. Is there a way to incorporate some type of timer so that the message fades out after several seconds? Has anyone else found a good solution for this?
Is it truly important to clear the status though? There are plenty of products which will keep their status label unchanged until the next status event occurs. Visual Studio is a good example of this. It may be worth simplifying your scenario and taking this approach.
If you do want to clear the status after an event I think the most maintainable way to do this is with a Timer. Essentially clear after a few seconds when the status is set
Timer m_timer;
void SetStatus(string text) {
m_statusLabel.Text = text;
m_timer.Reset();
}
void OnTimerTick(object sender, EventArgs e) {
m_statusLabel.Text = "";
m_timer.Stop();
}
Yes a timer would work for this to clear it. Here is an example of one I've knocked together.
public partial class Form1 : Form
{
private System.Timers.Timer _systemTimer = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_systemTimer = new System.Timers.Timer(500);
_systemTimer.Elapsed += _systemTimer_Elapsed;
}
void _systemTimer_Elapsed(object sender, ElapsedEventArgs e)
{
toolStripStatusLabel1.Text = string.Empty;
_systemTimer.Stop(); // stop it if you don't want it repeating
}
private void button1_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "random text just as an example";
}
private void button2_Click(object sender, EventArgs e)
{
_systemTimer.Start();
}
}
Assume button1 is your action to update the status, and button2 is just a random way to start the timer (this can be however you want to start it, I've only used another button click as an example). After the set amount of time passes the status label will be cleared.

Updating a textbox using no input controls

I have a windows form application which consists of a bunch of controls, but more specifically, two textBoxes. One of them is read only. The read only textBox value is supposed to be the same as the textBox that the user can type into.
So if the user types "Hello World" into textBox A, the value in textBox B should be automatically updated to "Hello World".
How do I go about doing this? I know I just need to set the text values, I'm just not sure where I place the code to get it done automatically rather than executed when a button is click or something along those lines.
TextChanged event:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = textBox1.Text;
}
It sounds like you want something like:
writableTextBox.TextChanged += delegate {
readonlyTextBox.Text = writableTextBox.Text;
};
In other words, whenever the text in one textbox changes, update the other. This uses the Control.TextChanged event.
If you want textBoxB to be updated as soon as the text of textBoxA is changed (i.e immediately after the user press a key in textBoxA) the event is TextChanged:
this.textBoxA.TextChanged += new System.EventHandler(this.textBoxA_TextChanged);
private void textBoxA_TextChanged(object sender, EventArgs e)
{
textBoxB.Text = textBoxA.Text;
}
If you prefer to update the text in textBoxB only after the user has finished to edit textBoxA, you should use the Leave event:
this.textBoxA.Leave += new System.EventHandler(this.textBoxA_Leave);
private void textBoxA_Leave(object sender, EventArgs e)
{
textBoxB.Text = textBoxA.Text;
}
This should do what you need:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = textBox1.Text;
}
Even shorter (better?) than the event approach is using winform's databinding. Just use this right after the InitializeComponents call:
readonlyTextBox.DataBindings.Add("Text", writableTextBox, "Text");

Categories