I'm currently writing a function that creates button in XAML (on runtime) according to JSON information that is received from an API call in C#.
I currently have the following code:
Button downloadButton = new Button();
downloadButton.Click += new RoutedEventHandler(DownloadContent);
But I get the following error:
An object reference is required for the non-static field, method, or property 'Mainwindow.DownloadContent(object, RoutedEventArgs)'
I've tried changing it to downloadButton.Click += new RoutedEventHandler(this, DownloadContent); but that gives me the error:
Keyword 'this' is not valid in a static property, static method, or static field initializer
For reference this is what DownloadContent looks like
private void DownloadContent(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("API-URL"), contentZip);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(InstallContent);
}
This is what I want the button to look like (skipping the other stuff like background color, etc.)
<Button Name="Downloadbutton"
Content="Download"
Click="DownloadContent"
</Button>
Am I missing something as why I get this Error and how could I fix it?
EDIT
The Installcontent function looks like this:
private void InstallContent(object sender, AsyncCompletedEventArgs e)
{
ZipFile.ExtractToDirectory(contentZip, contentPath, true);
File.Delete(contentZip);
writeJsonData(DLCbuttonTag);
Downloadbutton.Visibility = Visibility.Collapsed;
Uninstallbutton.Visibility = Visibility.Visible;
}
The function that creates the button:
public static void getContentList()
{
string jsonString = File.ReadAllText(@"C:\Users\stage\OneDrive\Documenten\ContentInfo.json")
ContentList contentList = JsonConvert.DeserializeObject<ContentList>(jsonString);;
for (int i = 0; i < contentList.Content.Count; i++)
{
StackPanel dynamicStackPanel = new StackPanel();
dynamicStackPanel.Orientation = Orientation.Horizontal;
dynamicStackPanel.Background = Brushes.Transparent;
Button downloadButton = new Button();
downloadButton.Click += new RoutedEventHandler(DownloadContent);
dynamicStackPanel.Children.Add(downloadButton);
}
}