如何识别单击的按钮属于哪个列表框项? [英] How to identify the clicked button belongs to which listbox item?

查看:53
本文介绍了如何识别单击的按钮属于哪个列表框项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF编程中,我在编写按钮单击事件处理程序时遇到问题.因为该按钮位于列表框项目(数据模板的一部分)内,并且单击该按钮时,我无法知道它属于哪个项目.有什么解决办法吗?SOS--

In WPF programming, I have a problem to write the button click event handler. Because the button is inside a listbox item(a part of datatemplate), and when the button is clicked, I can't tell which item it belongs to. Is there any solution? SOS - -

推荐答案

似乎您已将列表框绑定到集合,并且按钮是数据模板或项目模板的一部分.
您可以将按钮的 Tag 属性绑定到数据对象:

It seems that you have bound a list box to a collection, and your buttons are part of your Data Template or Item Template.
You can bind the Tag property of the buttons to your data object:

<DataTemplate DataType="{x:Type c:Person}">
    <StackPanel Orientation="Vertical">
        <StackPanel Orientation="Horizontal">
            <TextBlock>Name:</TextBlock>
            <TextBlock Text="{Binding Path=Name}"/>
        </StackPanel>
        <Button Click="Button_Click" Tag="{Binding Path=.}">Click me!</Button>
    </StackPanel>
</DataTemplate>

点击事件:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button b = (Button)sender;
    Person p = (Person)b.Tag;
    MessageBox.Show(p.Name);
}

但是,正如其他人所建议的那样,您可以使用Button的 DataContext 属性.在我的示例中,它已经指向 Person 对象.

But, as other people suggest, you can use the DataContext property of the Button. It already points to the Person object in my example.

我认为通过使用 Tag 属性,您可以更好地控制要在事件处理程序中访问的内容.

I think by using the Tag property, you have more control over what you want to access in you event handler.

有很多方法可以完成所有工作!选择最适合您的那个.

There are many ways to do everything! Choose the one that best suits you.

这篇关于如何识别单击的按钮属于哪个列表框项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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