我正在使用 XamlReader.Parse(string) 动态构建我的数据模板。我遇到的问题是我无法在使用 XamlReader 创建的任何控件上放置任何事件。在网上做了一些研究后,我了解到这是 XamlReader 的一个已知限制。
我对 WPF 中的命令了解不多,但我可以以某种方式使用它们来获得相同的结果吗?如果是这样怎么办?如果没有,有什么方法可以处理使用 Xaml Reader 创建的控件中的代码隐藏事件吗?
下面是我创建的数据模板的示例。我在将托管此数据模板的窗口的代码隐藏中定义了 MenuItem_Click 事件处理程序。
尝试运行它时出现以下错误: System.Windows.Markup.XamlParseException 未处理:无法从文本“MenuItem_Click”创建“单击”。
DataTemplate result = null;
StringBuilder sb = new StringBuilder();
sb.Append(@"<DataTemplate
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Grid Width=""Auto"" Height=""Auto"">
<TextBlock Text=""Hello"">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem
Header=""World""
Click=""MenuItem_Click""></MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</Grid>
</DataTemplate>");
result = XamlReader.Parse(sb.ToString()) as DataTemplate;
希望迟来的答案可以帮助其他人:
我发现我需要解析后绑定事件,并且必须从 Xaml 字符串中删除单击事件。
在我的场景中,我将生成的 DataTemplate 应用到 DataTemplate,连接 ItemSsource,然后添加处理程序。这确实意味着所有项目的点击事件都是相同的,但就我而言,标题是所需的信息,并且方法是相同的。
//Set the datatemplate to the result of the xaml parsing.
myListView.ItemTemplate = (DataTemplate)result;
//Add the itemtemplate first, otherwise there will be a visual child error
myListView.ItemsSource = this.ItemsSource;
//Attach click event.
myListView.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(MenuItem_Click));
然后点击事件需要返回到原始来源,在我的例子中,发送者将是使用 DataTemplate 的 ListView。
internal void MenuItem_Click(object sender, RoutedEventArgs e){
MenuItem mi = e.OriginalSource as MenuItem;
//At this point you can access the menuitem's header or other information as needed.
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)