您可以使用数据绑定到按钮的标签绑定到其ListBox
祖先例:
<Grid>
<Grid.Resources>
<DataTemplate x:Key="myDataTemplate">
<Button Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}}"
Click="Button_Click">MyButton</Button>
</DataTemplate>
</Grid.Resources>
<ListBox ItemTemplate="{StaticResource myDataTemplate}" ItemsSource="..." />
</Grid>
而这里的隐藏代码:
private void Button_Click(object sender, RoutedEventArgs e)
{
ListBox myListBox = (ListBox)((Button)sender).Tag;
...do something with myListBox...
}
或者,您可以手动CL在你的代码中向上看im树(不需要Tag
数据绑定):
private void Button_Click(object sender, RoutedEventArgs e)
{
DependencyObject search = (DependencyObject)sender;
while (!(search is ListBox)) {
search = VisualTreeHelper.GetParent(search);
}
ListBox myListBox = (ListBox)search;
...do something with myListBox...
}
为什么你需要手动重新加载ListBox?如果你的数据源有某种通知机制(例如,如果它是一个'BindingList'),ListBox应该自动注意到它的ItemSource已经改变了。 – Heinzi 2010-04-01 22:02:18