我正在尝试动态添加UI元素,但我遇到了一个问题,我能够添加UI元素,但是我无法将点击事件添加到按钮上。
以下是我的代码:
如果我删除了这个
它会起作用。但如果我添加它,它会显示如下内容:
有人知道如何解决吗?
提前感谢。
以下是我的代码:
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);
我的 onClick 函数:
private void btnMy_Click(object sender, RoutedEventArgs e)
{
var myValue = ((Button)sender).Tag;
MessageBox.Show("Here = " + myValue);
}
对于这行代码:
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'>";
如果我删除了这个
标签
。Click='btnMy_Click'
它会起作用。但如果我添加它,它会显示如下内容:
![enter image description here](https://istack.dev59.com/0PHRL.webp)
XamlReader.Parse
不支持事件处理程序。如果支持,至少需要一些上下文信息才能解析事件处理程序方法。您是否有在运行时解析XAML而不是使用数据模板或仅切换UI元素的可见性的特定原因? - Pieter Witvoet