有沒有辦法配置WPF ListBox
,使其無法取消選擇/取消選擇項目?所以總是選擇一個項目?不允許在列表框中取消選擇/取消選擇
我的ListBox
綁定到ObservableCollection<MyClass>
。
有沒有辦法配置WPF ListBox
,使其無法取消選擇/取消選擇項目?所以總是選擇一個項目?不允許在列表框中取消選擇/取消選擇
我的ListBox
綁定到ObservableCollection<MyClass>
。
如果SelectedItem
的計算結果爲null
,您可以處理SelectionChanged
事件並設置一個選擇。要重新選擇一個未被選中的項目,您可以跟蹤私有字段中的最後一個選定項目,該項目應始終在SelectionChanged
事件中更新。
也許不是最優雅的解決方案,但它對我有效,謝謝! – 2011-05-03 11:56:53
確實不算高雅,但我很高興它爲你工作。 – 2011-05-03 13:09:40
在SelectionChanged中,您在SelectionChangedEventArgs中擁有RemovedItems。所以你不需要跟蹤上次選擇的項目,它也適用於多選列表框。 – Matt 2015-06-11 13:33:35
聽起來更像一個RadioButtonGroup。你可以自定義列表框的ItemContainerStyle,輕鬆地在你的下面listboxes.See
<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>
這種行爲檢查以下鏈接更多
http://drwpf.com/blog/2009/05/12/itemscontrol-l-is-for-lookless/
在選擇項目後,您可以禁用ListBox。 – IVerzin 2011-04-28 09:33:24