wpf中我在每个listboxItem里都加了一个按钮,点击按钮后,如何知道点击的按钮是属于哪个item呢?

如题所述

其实这个可以通过绑定父控件的属性来实现,给个Demo
前台:
<Grid>
<ListBox>
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Button Content="click" Margin="0,2" Width="50" Height="25" Click="Button_Click"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
<ListBoxItem Tag="1"/>
<ListBoxItem Tag="2"/>
<ListBoxItem Tag="3"/>
</ListBox>
</Grid>
后台:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;

RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor);
rs.AncestorType=typeof(ListBoxItem);

Binding binding = new Binding("Tag") { RelativeSource=rs};

btn.SetBinding(Button.ContentProperty,binding);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-03-29
ListBoxItem本身就是可选的,你要操作的话,可以给ListBoxItem的Selected属性添加事件,SelectedIndex值里面存了Item的序号的,值从0开始的。
相似回答