列表框未检测到所选项目

时间:2012-06-28 14:05:50

标签: wpf

我有以下列表框:

<ListBox ItemsSource="{Binding AvailableTemplates}" Style="{DynamicResource SearchListBoxStyle}" SelectedItem="{Binding SelectedTemplate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <RadioButton Content="{Binding}" GroupName="group" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

如果我在单选按钮上选择,则不会检测到所选项目已更改。它只检测我是否在列表框行上的单选按钮下单击。任何想法如何在单击单选按钮时如何修改以检测所选项目?

3 个答案:

答案 0 :(得分:8)

如果您只想将RadioButton.IsCheckedListBoxItem.IsSelected同步,则可以使用绑定

<RadioButton Content="{Binding}" GroupName="group"
             IsChecked="{Binding Path=IsSelected, RelativeSource={
                 RelativeSource AncestorType={x:Type ListBoxItem}},Mode=TwoWay}"/>

如果您不希望自己的项目同步,那么每当项目获得键盘焦点时,您都​​可以使用设置Trigger的{​​{1}},但这只会保留一个项目,只要它有键盘焦点

IsSelected

如果你想要它被选中,无论元素是否仍然具有键盘焦点,你必须使用一些代码

<Style TargetType="ListBoxItem">
  <Style.Triggers>
    <Trigger Property="IsKeyboardFocusWithin" Value="True">
      <Setter Property="IsSelected" Value="True" />
    </Trigger>
  </Style.Triggers>
</Style>
<Style TargetType="{x:Type ListBoxItem}">
    <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>

答案 1 :(得分:1)

你不能错:listBox.SelectedItem和radioButton.IsChecked

他们是完全不同的东西, SelectedItem被称为ListBoxItem,您的radiobutton在listboxitem中。

您必须对属性IsChecked(RadioButton)进行绑定。

答案 2 :(得分:1)

尝试将ListBoxItem.IsHitTestVisible设置为false(您可以在xaml中执行此操作)。它解决了我的选择问题。我的问题是,只有当我点击ListBox行中的空格而不是自定义内容时,选择才有效。