首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >单击ListBoxItem内部的控件时,不选择ListBoxItem

单击ListBoxItem内部的控件时,不选择ListBoxItem
EN

Stack Overflow用户
提问于 2014-06-11 09:31:28
回答 2查看 2.1K关注 0票数 3

嗨,我找不到任何类似的问题,所以我发布了新的问题。在下面的代码中,我创建了ListBox控件,其中每个ListBoxItems都包含单选按钮。当我单击单选按钮时,它会得到选择,但父ListBoxItem不会(ListBoxItem没有突出显示)。我怎样才能解决这个问题?

代码语言:javascript
复制
<ListBox Margin="0, 5, 0, 0" ItemsSource="{Binding mySource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!-- Rabio template -->
            <RadioButton GroupName="radiosGroup"
                     Margin="10, 2, 5, 2"
                     Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.SelectedSetting}"
                     CommandParameter="{Binding SomeId, Mode=OneWay}"
                     Content="{Binding FileNameWithoutExtensions, Mode=OneWay}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-11 09:37:10

您可以通过将下面的ItemContainerStyle应用到您的ListBox中来实现这一点,它使用属性IsKeyboardFocusWithin上的Trigger来选择它。

代码语言:javascript
复制
<ListBox>
    <ListBox.ItemContainerStyle>
      <Style TargetType="ListBoxItem">
         <Style.Triggers> 
           <Trigger Property="IsKeyboardFocusWithin" Value="True"> 
              <Setter Property="IsSelected" Value="True"/> 
           </Trigger> 
         </Style.Triggers>
       </Style>
    </ListBox.ItemContainerStyle>
</ListBox>
票数 7
EN

Stack Overflow用户

发布于 2022-01-11 16:49:26

我有一个列表框,它垂直地、水平地显示ListBoxItem的,并且在每个ListBoxItem中包含各种子按钮。

我遇到的问题(和其他人一样)是,当您单击ListBoxItem中包含的子按钮时,没有选择ListBoxItem,也无法获得ListBoxItem.SelectedIndex值(因为单击按钮不会选择ListBoxItem)。

实现上述xaml代码时遇到了一些问题,因为单击GroupBox头会导致所选的ListBoxItem失去焦点。

对于这个问题,我在网上找到的最佳解决方案是向按钮的鼠标单击事件中添加几行代码,以确定父控件,然后设置ListBoxItem.IsSelected = true

完成此操作后,ListBoxItem.SelectedIndex将包含所选项的正确索引值。在我的代码中,DataContext设置在列表框上,如下所示:DataContext="{StaticResource VM_Programs}"

下面是按钮事件背后的VB代码:

代码语言:javascript
复制
Private Sub YourButton_Click(sender As Object, e As RoutedEventArgs)
    Dim clicked As Object = (TryCast(e.OriginalSource, FrameworkElement)).DataContext
    Dim lbitem As ListBoxItem
    lbitem = YourListboxName.ItemContainerGenerator.ContainerFromItem(clicked)
    lbitem.IsSelected = True
    MsgBox("The listbox item (" + YourListboxName.SelectedIndex.ToString + ") is now selected")
End Sub
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24159382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档