[英]How to Synchronize ListBox SelectedItem and the focused item in WPF?
我將按鈕創建為 ListBox 項。 使用鍵盤快捷鍵,所選項目/按鈕將更改為第一個字符與按下的鍵相同的按鈕。 問題是焦點項目(虛線矩形)不會與所選項目同步。 如果我們使用鍵盤箭頭,則不存在此問題。 縮短的代碼是:
<ListBox x:Name="ListBoxRef"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
DataContext="{Binding Path=ListViewSource}" IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Tag="{Binding}" IsTabStop="False"
Command="{Binding ElementName=UserControlTypeSelectionView, Path=DataContext.SelectCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}}">
<Button.Template>
<ControlTemplate>
<TextBlock Text="{Binding Path=Name}" />
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
在如何以編程方式將焦點設置到已具有焦點的 WPF ListBox 中的 SelectedItem? ,解決方案是使用Focus方法並在C#端。
是否可以在 MVVM 中僅使用 XAML?
我從同事那里找到了答案。 通過使用當前選定的項目設置器(IsSelected屬性)觸發FocusManager.FocusedElement可以解決此問題。
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<!-- Edited: add pushpraj code to hide the dashed rectangle on focused item -->
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
如果您對焦點(虛線)矩形不感興趣,而僅對純xaml解決方案感興趣,則可以將其隱藏
這是一個樣本
<ListBox>
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="FocusVisualStyle"
Value="{x:Null}" />
</Style>
</ListBox.Resources>
<ListBoxItem>item 1</ListBoxItem>
<ListBoxItem>item 2</ListBoxItem>
<ListBoxItem>item 3</ListBoxItem>
</ListBox>
該示例中有趣的區域是ListBoxItem
的Style
,該Style
為FocusVisualStyle
設置了一個空值,通常為虛線矩形。
這不等同於將焦點元素與所選項目同步,但是它隱藏了焦點層,因此不會顯示虛線矩形。
@YohanesNurcahyo,只有當 ListBox SelectionMode
設置為Single
時才是很好的答案。 這是我的更新:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<!-- Edited: add pushpraj code to hide the dashed rectangle on focused item -->
<Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="True" />
<Condition Binding="{Binding RelativeSource={RelativeSource AncestorType=ListBox}, Path=SelectionMode}" Value="Single" />
</MultiDataTrigger.Conditions>
<Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
否則,如果有的話,它會破壞多重選擇(前提是 ListBox SelectedItems 屬性只讀限制已被覆蓋)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.