I have a FileSystemWatcher that checks a folder for changes, of course. So when you add a file to the folder I need to add a button to a wrappanel. I have tried:
public void CheckDir()
{
string[] args = System.Environment.GetCommandLineArgs();
var folderName = $"{AppDomain.CurrentDomain.BaseDirectory}games";
FileSystemWatcher watcher = new FileSystemWatcher
{
Path = folderName,
NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName
};
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
//When button is changed, created, or deleted
private void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.Name + " " + e.ChangeType);
var buttonName = "Button_" + Path.GetFileNameWithoutExtension(e.FullPath).Replace(" ", "");
if (e.ChangeType == WatcherChangeTypes.Created)
{
var buttonContent = Path.GetFileNameWithoutExtension(e.FullPath);
CreateButton(buttonContent, buttonName);
}
else if (e.ChangeType == WatcherChangeTypes.Deleted)
{
buttonHolder.Children.Remove(btnFile);
}
}
And the CreateButton void:
private void CreateButton(string buttonContent, string buttonName)
{
Button newBtn = new Button
{
Content = buttonContent,
Name = buttonName,
BorderThickness = new Thickness(1),
Width = 260,
Height = 100
};
newBtn.Click += OpenFile;
buttonHolder.Children.Add(newBtn);
}
But I get an error when trying to add the button:
The calling thread must be STA, because many UI components require this.
And I have no idea what to change or what the error means, and yes, I've searched for it, but could not find a solution or good explanation to what it is.