Reputation: 35
I'm a real beginner "coder", and I have work, to make an autochanging photo
with a textbox
(write xy sec, it will be the time between 2 image)
string path = @"C:\Teszt\";
string[] Files = Directory.GetFiles(path, "*.jpg");
List<string> fileList = new List<string>();
foreach (var item in Files)
{
fileList.Add(item);
}
for (int i = 0; i < fileList.Count; i++)
{
string year= "";
year += DateTime.Now.Year;
string month = "";
month += DateTime.Now.Month;
string day = "";
day += DateTime.Now.Day;
//update textbox
Date.Content = year + "." + month + "." + day + ".";
string filepath = fileList[i];
var urii = new Uri(filepath);
var bitmaap = new BitmapImage(urii);
image.Source = new BitmapImage(new Uri(fileList[i]));
Thread.Sleep(TimeSpan.FromSeconds(10));
if (i == fileList.Count)
i = 0;
}
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
Thread.Sleep(TimeSpan.FromSeconds(int.Parse(this.TextBox.Text)));
}
Upvotes: 2
Views: 84
Reputation: 8643
One thing you will want to do is split up your code in methods that have a clear, single responsibility. this makes your programs easier to understand
The Date-in-a-textbox code has no business inside that loop
You will need a way to do the waiting until the next picture in the background, so it will not block your UI thread, still allowing you to enter text in the textbox. The dispatcherTimer is a good way to go.
you need to make sure the text in the textbox can be parsed to a number before doing anything
private List<string> kepek = new List<string>();
private int képnévIndex = 0;
private DispatcherTimer timer;
//this is my stand-in for your constructor. you didn't put it in the example, so i'm using "myClass"
public myClass()
{
// you will still need InitializeComponent();
InitializeComponent();
LoadImages();
setupTimer(10);
displayCurrentDate();
}
private void setupTimer(int timeoutInSeconds)
{
if(timer != null)
{
timer.Stop();
}
timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(timeoutInSeconds) };
timer.Tick += (sender, args) =>
{
showNextPicture();
};
timer.Start();
}
private void LoadImages()
{
string path = @"C:\Teszt\";
string[] Files = Directory.GetFiles(path, "*.jpg");
foreach (var item in Files)
{
kepek.Add(item);
}
}
private void displayCurrentDate()
{
string év = "";
év += DateTime.Now.Year;
string hónap = "";
hónap += DateTime.Now.Month;
string nap = "";
nap += DateTime.Now.Day;
Date.Content = év + "." + hónap + "." + nap + ".";
}
private void showNextPicture()
{
string képnév = kepek[képnévIndex];
image.Source = new BitmapImage(new Uri(képnév));
képnévIndex++;
if (képnévIndex == kepek.Count)
képnévIndex = 0;
}
private void Szövegdoboz_TextChanged(object sender, TextChangedEventArgs e)
{
int parsedNumberOfSeconds;
//if we entered something that can not be parsed to a number, exit.
if(!int.tryParse(Szövegdoboz.Text, out parsedNumberOfSeconds))
return;
setupTimer(parsedNumberOfSeconds);
}
Upvotes: 2