簡體   English   中英

WPF:當您按下此ListItem上的按鈕時,ListItem不會獲得焦點

[英]WPF: ListItem does not receive focus when you press the button located on this ListItem

我有一個帶DataTemplateListBox 模板上有一個Button 列表中的每個項目都顯示實體。

<ListBox Grid.Column="0"
             x:Name="ThemesList"
             ItemsSource="{Binding Themes}"
             HorizontalAlignment="Left"
             VerticalAlignment="Top"
             SelectedItem="{Binding SelectedTheme}" 
             ItemTemplate="{StaticResource ThemeListTemplate}"/>

<DataTemplate x:Key="ThemeListTemplate">
    <Grid Grid.Column="1"
          Grid.Row="0"
          HorizontalAlignment="Right" 
          Margin="10">

          <Grid.RowDefinitions>
              <RowDefinition/>
              <RowDefinition/>
          </Grid.RowDefinitions>

          <Button Grid.Row="0" 
                  HorizontalAlignment="Left"
                  Style="{StaticResource ElementButton}"
                  Command="{Binding Path=DataContext.ThemeEditorViewModel.OpenThemeEditorCommand, ElementName=ThemesBacklog}"
                  CommandParameter="{Binding Path=SelectedItem, ElementName=ThemesList}">

                <TextBlock Text="Edit"/>
          </Button>

        <Button Grid.Row="1" 
                HorizontalAlignment="Left"
                Style="{StaticResource ElementButton}"
                Command="{Binding Path=DataContext.ThemeDeleteCommand, ElementName=ThemesBacklog}"
                CommandParameter="{Binding Path=SelectedItem, ElementName=ThemesList}">

                <TextBlock Text="Delete"/>
        </Button>
    </Grid>
</DataTemplate>

當您在命令中單擊Button ,將傳遞屬性值SelectedItem 當您單擊ListItem ,然后單擊Button -很好。 當我一次單擊Button -在命令中傳遞null。 也就是說,當您按下位於此ListItem上的按鈕時, ListItem不會獲得焦點。 如何解決這個問題呢?

您可以在觸發器中檢查ListBoxItems上的IsKeyboardFocusWithin屬性,以找出子對象(如按鈕)是否具有焦點,並在這種情況下將IsSelected設置為true。

您可以通過如下設置ItemContainerStyle做到這一點:

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
        <Style.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter Property="IsSelected" Value="True" />
            </Trigger>
        </Style.Triggers>
    </Style>
</ListBox.ItemContainerStyle>

暫無
暫無

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

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