Is there a way to configure the WPF ListBox
such that it's not possible to deselect/unselect an item? So there is always an item selected?
My ListBox
binds to an ObservableCol开发者_JS百科lection<MyClass>
.
You can handle the SelectionChanged
event and set a selection if the SelectedItem
evaluates to null
. To reselect an item that has been unselected you can keep track of the last selected item in a private field, which should always be updated in the SelectionChanged
event.
Sound more like a RadioButtonGroup.You can customize the ItemContainerStyle of listbox and easily have this behavior in your listboxes.See below
<Style TargetType="{x:Type RadioButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RadioButton}">
<Border
Name="Border"
Padding="2"
SnapsToDevicePixels="true">
<Grid
VerticalAlignment="Center">
<ContentPresenter x:Name="contentPresenter"
TextBlock.FontWeight="Bold"
TextBlock.Foreground="{TemplateBinding Foreground}"
TextBlock.FontSize="10"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="true">
<Setter TargetName="Border" Property="Background"
Value="{StaticResource SelectedBackgroundBrush}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground"
Value="{StaticResource DisabledForegroundBrush}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ObjectDataProvider x:Key="WindowStyles" MethodName="GetValues"
ObjectType="{x:Type sys:Enum}" >
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="WindowStyle" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<Style x:Key="RadioButtonList" TargetType="{x:Type ListBox}">
<Setter Property="BorderBrush" Value="{x:Null}" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Margin" Value="6,2" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Background="Transparent">
<RadioButton Focusable="False"
IsHitTestVisible="False"
IsChecked="{TemplateBinding IsSelected}">
<ContentPresenter />
</RadioButton>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<StackPanel Margin="10">
<TextBlock FontWeight="Bold">WindowStyle:</TextBlock>
<ListBox Name="WindowStyleSelector" SelectedIndex="1" Margin="10,0,0,0"
Style="{StaticResource RadioButtonList}" Tag="Horizontal"
ItemsSource="{Binding Source={StaticResource WindowStyles}}" />
</StackPanel>
</Grid>
Check the below link for more
http://drwpf.com/blog/2009/05/12/itemscontrol-l-is-for-lookless/
精彩评论