get clicked button content from button styled listbox binded to xml

自闭症网瘾萝莉.ら 提交于 2019-11-28 06:34:30

问题


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.

Here is my code

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>

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);
     }

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.


回答1:


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 : 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.




回答2:


I know you got the answer but, this is another type to get the content of button.

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


来源:https://stackoverflow.com/questions/11404918/get-clicked-button-content-from-button-styled-listbox-binded-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!