Skip to main content
 首页 » 编程设计

c#之调整 WPF ListBox 选择框的大小

2024年02月20日12虾米姐

对于一个项目,我实现了一个类似于 ListBox 的小型 IntelliSense 控件。它的 DataTemplate 由一个 StackPanel 组成,其中包含一个 Image 和一个 TextBlock。没有其他的。正如您在我的控件的第一个屏幕截图中看到的那样,ListBox 的选择框选择了整个项目(这通常正是人们所期望的):

但是我从 VS11 中“偷来”的图标质量很差,所以我想像 Visual Studio 那样调整选择:

您可以看到仅选择了文本(视觉表示确实忽略了图像/图标),我也想知道如何实现此行为。

编辑:图标只是具有透明背景的 GIF 文件。我会用更好的替换它们,但我仍然对如何获得所需的行为感兴趣。

请您参考如下方法:

这是一个通过替换 ListBoxItem 控件模板的解决方案。在我的测试中,我只显示两个文本字符串,第二个字符串突出显示。

<Page.Resources> 
    <Style x:Key="ItemStyle" TargetType="ListBoxItem"> 
        <Setter Property="Template"> 
            <Setter.Value> 
                <ControlTemplate TargetType="ListBoxItem"> 
                    <ContentPresenter/> 
                </ControlTemplate> 
            </Setter.Value> 
        </Setter> 
    </Style> 
 
    <Style x:Key="Selected" TargetType="{x:Type TextBlock}"> 
        <Style.Triggers> 
            <DataTrigger Binding="{Binding Path=IsSelected,  
                         RelativeSource={RelativeSource Mode=FindAncestor,  
                         AncestorType={x:Type ListBoxItem}}}" Value="True"> 
                <Setter Property="Background"  
                        Value="{x:Static SystemColors.HighlightBrush}"/> 
            </DataTrigger> 
        </Style.Triggers> 
    </Style> 
 
    <DataTemplate x:Key="ItemTemplate" DataType="{x:Type ViewModel:DataItem}"> 
        <Grid> 
            <Grid.ColumnDefinitions> 
                <ColumnDefinition Width="auto" SharedSizeGroup="c1"/> 
                <ColumnDefinition Width="auto" SharedSizeGroup="c2"/> 
                <ColumnDefinition Width="*"/> 
            </Grid.ColumnDefinitions> 
            <Image Source="../Images/Collapse.png"/> 
            <TextBlock Grid.Column="1" Text="{Binding Name}" Margin="0,0,5,0"/> 
            <TextBlock Style="{StaticResource Selected}"  
                       Grid.Column="2" Text="{Binding Description}"/> 
        </Grid> 
    </DataTemplate> 
</Page.Resources> 
 
<Page.DataContext> 
    <Samples:Page3ViewModel/> 
</Page.DataContext> 
 
<Grid> 
    <ListBox  
        Grid.IsSharedSizeScope="True" 
        SelectedIndex="2" 
        HorizontalContentAlignment="Stretch" 
        ItemsSource="{Binding Items}"  
        ItemContainerStyle="{StaticResource ItemStyle}" 
        ItemTemplate="{StaticResource ItemTemplate}"/> 
</Grid> 

View 模型包含一组简单的数据项

public class Page3ViewModel 
{ 
    public Page3ViewModel() 
    { 
        Items = new List<DataItem> 
            { 
                new DataItem{Name = "One", Description = "First"}, 
                new DataItem{Name = "Two", Description = "Second"}, 
                new DataItem{Name = "Three", Description = "Third"}, 
                new DataItem{Name = "Four", Description = "Fourth"}, 
            }; 
    } 
    public IEnumerable<DataItem> Items { get; private set; } 
} 

给予