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);
}
前台:
<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);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询