I am a newbie to wpf and i am doing some poc on wpf controls.I have created the buttons dynamically by reading from my xml file and i placed the buttons inside a stackpanel.i want to write the click event of the button by clicking on it and i wrote a click event which gives all the button names inside the stack panel but what i want is i want to get the respective button name when i click.
My XML FILE:
<root>
<Project Name="FundsCrossReferences" Label ="SMA Model Management" LibraryName="SMAMC" ClassName="" Roles="">
</Project>
<Project Name="SMAFI" Label ="SMAFI" LibraryName="SMAFI" ClassName="" Roles="">
</Project>
</root>
My window.xaml.cs file
private void windowloaded()
{
StringBuilder result = new StringBuilder();
foreach (XElement level1Element in XElement.Load(@"C:\Users\Trial\XMLFile.xml").Elements("Project"))
{
result.AppendLine(level1Element.Attribute("Name").Value+"/");
}
List<string> addnames = new List<string>();
string[] stringArray = result.ToString().Split('/').ToArray();
stringArray = stringArray.Take(stringArray.Count() - 1).ToArray();
foreach (var arrayname in stringArray)
{
var names = arrayname.Replace("\r\n", "");
addnames.Add(names);
}
List<string> list = addnames.ToList();
foreach(var buttoname in list)
{
var newButton = new Button() { Name= buttoname,Height=39,Foreground=Brushes.Black,Content=buttoname};
this.mainpanel.Children.Add(newButton);
}
}
My Window.xaml:
<StackPanel x:Name="mainpanel"></StackPanel>
Kindly help me with the click event of buttons or the name of the button which is clicked inside the stackpanel.
Just hook up a click event handler in the foreach
loop:
newButton.Click += Your_Handler;