I am trying to add UI elements dynamically, but I am facing a problem, I able to add UI elements, but I fail to add click event to Button
Below is my code :
ParserContext context = new ParserContext();
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
string xaml = String.Format(" <StackPanel Orientation='Vertical'>");
xaml = xaml + "<StackPanel Orientation='Horizontal'>";
xaml = xaml + "<Button Margin='5,5,0,0' Background='AliceBlue' Foreground='DarkBlue' Height='25' VerticalAlignment='Bottom' HorizontalAlignment='Right' Width='82' Tag='12' Click='btnMy_Click'>";
xaml = xaml + "<StackPanel Orientation='Horizontal'>";
xaml = xaml + "<Image Source='/MotionTest;component/images/open.png' Width='18' Height='18' />";
xaml = xaml + "<TextBlock Text=' Open' VerticalAlignment='Center' FontSize='13' />";
xaml = xaml + "</StackPanel>";
xaml = xaml + "</Button>";
xaml = xaml + "</StackPanel>";
xaml = xaml + "</StackPanel>";
UIElement element = (UIElement)XamlReader.Parse(xaml, context);
myTestGrid.Children.Add(element);
And my onClick function :
private void btnMy_Click(object sender, RoutedEventArgs e)
{
var myValue = ((Button)sender).Tag;
MessageBox.Show("Here = " + myValue);
}
For this line :
xaml = xaml + "<Button Margin='5,5,0,0' Background='AliceBlue' Foreground='DarkBlue' Height='25' VerticalAlignment='Bottom' HorizontalAlignment='Right' Width='82' Tag='12' Click='btnMy_Click'>";
If I remove the
Click='btnMy_Click'
It will work. But if I add it, It shows
Anyone know how to solve this ? Thanks in advance.