如果你想选择ListBoxItem
按钮点击ListBoxItem你可以通过将点击处理程序附加到你的按钮来做到这一点。
假设你有这样的XAML的列表框声明:
<ListBox x:Name="listBox" ItemsSource="{Binding SourceCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Content="{Binding PropertyName}" Click="Button_Click"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
可以从处理程序选择一个ListBoxItem:按钮的
private void Button_Click(object sender, RoutedEventArgs e)
{
ListBoxItem selectedItem = (ListBoxItem)listBox.ItemContainerGenerator.
ContainerFromItem(((Button)sender).DataContext);
selectedItem.IsSelected = true;
}
访问DataContext
这将是相同的一个ListBoxItem。因此,你可以从ItemContainerGenerator
获得容器元素,即ListBoxItem。
设置IsSelected
到True
取回listBoxItem。
请稍等片刻 –