我在WPF中有一个列表框,当用户选择一个项目时,会显示一些不好看的颜色。我能不能让所有项目都不可选呢?
ItemsControl
而不是ListBox
。ItemsControl
无法像ListBox
那样完成一些可能需要的功能,比如在使用虚拟化时的ScrollIntoView
。 - Seth Carnegie<Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
<!-- Possibly other setters -->
<Setter Property="Focusable" Value="False" />
</Style>
<ListBox ItemsSource="{Binding YourCollection}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Focusable" Value="False"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
如果您不希望它们可选择,那么您可能不需要一个列表视图。 但如果这是您真正需要的,那么您可以使用样式来实现:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="{x:Type ListBoxItem}" TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border
Name="Border"
Padding="2"
SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="Background" Value="#DDDDDD"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="#888888"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<Grid>
<ListBox>
<ListBoxItem>One</ListBoxItem>
<ListBoxItem>Two</ListBoxItem>
<ListBoxItem>Three</ListBoxItem>
</ListBox>
</Grid>
</Page>
看一下IsSelected触发器。你可以将边框设置为不同的颜色,这样它就不会显得"丑陋",或者将其设置为透明,在选择时就不会可见。
希望这能帮到你。
ListBox
属性为 IsHitTestVisible="False"
。这会阻止列表中所有项目接收鼠标事件。这样做的好处是,可以停止鼠标悬停时的高亮显示。ScrollViewer
来重新建立滚动的原因。 - Denise Draper使用上面viky的答案,简单地实现这个功能的方法是在SelectionChanged()中将选定的索引设置为-1,如下所示。
public void OnListView_SelectionChanged(Object sender, RoutedEventArgs e)
{
if (null != sender && sender is ListView)
{
ListView lv = sender as ListView;
lv.SelectedIndex = -1;
}
}
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsEnabled" Value="False"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
... what you want as a source ...
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ListBox IsEnabled="False"/>
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
CanContentScroll="True" />
<ItemsControl>
....here my content....
</Itemscontrol>
</ScrollViewer>
对我来说按预期工作了。 敬礼, 丹尼尔