从绑定到 xml 的按钮样式列表框中获取单击的按钮内容 [英] get clicked button content from button styled listbox binded to xml

查看:12
本文介绍了从绑定到 xml 的按钮样式列表框中获取单击的按钮内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有一个绑定到 xml 文件的列表框,我为每个项目提供了一个按钮数据模板,这样我就可以轻松地为每个项目注册一个单击事件.

Hi I have a listbox binded to a xml file, and each item I gave them a button data template so I can easily register a click event to each item.

我很想得到点击按钮的内容来做一些查询.

I would love to get the clicked button's content to do some query on.

这是我的代码

XAML

<ListBox  Name="listBox1" >
        <ListBox.ItemsSource>
            <Binding Source="{StaticResource keywordLib}" XPath="Position/Keyword/Word"/>
        </ListBox.ItemsSource>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding}" Click="keyword_Click"/>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>

经过数小时的谷歌搜索后.我知道我应该使用 click 事件中的 sender,这对于普通按钮来说效果很好,这里没有说明.

After hours of googling for solutions. I know I should use sender from the click event, and that worked fine for a normal button, didn't word here.

    private void keyword_Click(Object sender, RoutedEventArgs e)
    { 
       Button btn = (Button)sender;
       String keyword = btn.Content.ToString();
       MessageBox.Show(keyword);
     }

消息框显示System.Xml.XmlElement".而不是按钮内容.

The messagebox showed "System.Xml.XmlElement". Instead of the button content.

非常感谢任何人可以帮助我解决这个问题.我花了这么多钱,我猜想解决办法只是一行代码.

Many thanks to anyone could help me out on this. I spend so much on this, and I could guess the solution is just one line code.

推荐答案

将按钮的内容转换为 System.Xml.XmlElement.然后使用该元素的 InnerText 属性.或者,您可能需要进行更多操作才能获得您的文本.这取决于您的 XML 文件是如何构建的.

cast the content of the button to an System.Xml.XmlElement. Then use the InnerText property of this element. Or maybe you have to do some more operation to get to your text. It depends on how your XML file is built.

Rq:当我需要区分代码中几个相同的控件时,我使用标签.所以我可以独立设置内容和标签(多语言应用程序需要.)甚至在选择标签(前缀/后缀,索引,...)时使用标签逻辑",从而简化代码处理.

Rq : when i need to distinguish several identical controls in code, i use Tags. So i can set content and Tag independantly (required for multi-language apps.) or even use a 'tag-logic'when choosing the Tag (prefixe/suffixes, index, ...) which simplify handling in code.

这篇关于从绑定到 xml 的按钮样式列表框中获取单击的按钮内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆