您可以使用數據綁定到按鈕的標籤綁定到其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