我使用XamlReader.Parse(string)动态构建我的数据模板。我遇到的问题是,我不能在使用XamlReader创建的任何控件上放置任何事件。在网上做了一些研究后,我了解到这是XamlReader的一个众所周知的局限性。
我对WPF中的命令了解不多,但我可以使用它们来获得相同的结果吗?如果是这样的话,是怎么做的?如果没有,有没有办法在我的代码后台处理使用Xaml Reader创建的控件中的事件?
下面是我创建的数据模板的一个示例。我在将承载此数据模板的窗口的代码中定义了MenuItem_Click事件处理程序。
当我尝试运行它时,我得到了以下错误:Click I unhandled:无法从文本‘MenuItem’创建一个‘System.Windows.Markup.XamlParseException’。
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;发布于 2012-02-10 03:11:49
希望晚一点的回答能帮助其他人:
我发现在解析之后需要单击绑定事件,并且必须从Xaml字符串中删除事件。
在我的场景中,我将生成的DataTemplate应用于ItemTemplate,连接ItemSource,然后添加处理程序。这确实意味着单击事件对于所有条目都是相同的,但在我的例子中,标题是所需的信息,方法是相同的。
//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.
}发布于 2010-08-21 00:01:20
看看this link吧。那里的大多数解决方案也将适用于Parse。我不是一个真正的C#开发人员,所以我唯一能解释的就是最后一个,这是一个如果所有其他都失败了的选项:
首先,将ID添加到XAML,而不是Click等属性。然后,您可以使用FindLogicalNode获取节点,然后自己连接事件。
例如,假设你给了你的MenuItem ID="WorldMenuItem"。然后,在调用parse之后的代码中,您可以这样做:
MenuItem worldMenuItem = (MenuItem)LogicalTreeHelper.FindLogicalNode(result, "WorldMenuItem");
worldMenuItem.Click += MenuItem_Click; // whatever your handler ishttps://stackoverflow.com/questions/3532287
复制相似问题