Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

wpf - get clicked button content from button styled listbox binded to 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...