我假设这是我所缺少的简单事情。
我ListBox
正在编写的WPF应用程序中有一个。每行都有一个按钮,可根据按钮所在的行执行简单的操作。如果用户直接单击按钮,则SelectedItem
onListBox
为null。如果我先单击SelectedItem
该行,则按预期单击该行的按钮。
我希望能够在单击按钮时选中该按钮所在的行。同样,我假设我缺少一些简单的东西,但是到目前为止,我的搜索是空的。
如果您要选择ListBoxItem
ListBoxItem的按钮单击,可以通过在按钮上附加单击处理程序来实现。
假设您有以下XAML用于ListBox声明:
<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的访问相同。因此,有了它,您可以从获得容器元素,即ListBoxItem ItemContainerGenerator
。
在获取的listBoxItem上设置IsSelected
为True
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句