簡體   English   中英

列表框未檢測到所選項目

[英]Listbox doesn't detect selected item

我有以下列表框:

<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>

如果我在單選按鈕上選擇,則不會檢測到所選項目已更改。 它僅檢測我是否單擊列表框行上的單選按鈕。 單擊單選按鈕時,是否有任何想法可以修改以檢測是否已更改所選項目?

如果只想將RadioButton.IsCheckedListBoxItem.IsSelected同步,則可以使用綁定

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

如果您不希望項目同步,則可以在項目獲得鍵盤焦點時使用一個設置為IsSelectedTrigger ,盡管只有在具有鍵盤焦點的情況下,它才會保持選中狀態

<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>
protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
    ListBoxItem item = (ListBoxItem)sender;
    item.IsSelected = true;
}

您不會誤會:listBox.SelectedItem和radioButton.IsChecked

它們是完全不同的東西,SelectedItem稱為ListBoxItem,您的單選按鈕位於listboxitem中。

您必須為屬性IsChecked(RadioButton)進行綁定。

嘗試將ListBoxItem.IsHitTestVisible設置為false(可以在xaml中執行此操作)。 它基本解決了我的選擇問題。 我的問題是,僅當我單擊ListBox行中的空白而不是自定義內容時,選擇才起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM