添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

在WPF中,实现ComboBox多选,并且可以根据输入值动态显示下拉框

34浏览 · 2024-03-21 19:39:04
在WPF中,实现ComboBox多选可以通过设置ComboBox的IsEditable属性为True,并使用一个TextBlock来[显示](https://geek.csdn.net/educolumn/103ca72607c717122e068b9f06a24df6?spm=1055.2569.3001.10083)选中项,同时在ComboBox的Popup部分添加一个ItemsControl用于[显示](https://geek.csdn.net/educolumn/103ca72607c717122e068b9f06a24df6?spm=1055.2569.3001.10083)下拉选项。当用户输入时,我们可以[动态](https://geek.csdn.net/educolumn/08aef4ab97997f5b9ed71860c44e8258?spm=1055.2569.3001.10083)地过滤下拉选项。以下是一个简单的实现示例: ```xml <ComboBox IsEditable="True" Text="{Binding SelectedText}" PreviewTextInput="ComboBox_PreviewTextInput" PreviewKeyDown="ComboBox_PreviewKeyDown"> <ComboBox.Template> <ControlTemplate TargetType="{x:Type ComboBox}"> <ToggleButton x:Name="ToggleButton" Content="{TemplateBinding SelectionBoxItem}" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, Rel[ati](https://geek.csdn.net/educolumn/150d7073277950db5f09620704e791cf?spm=1055.2569.3001.10083)veSource={Rel[ati](https://geek.csdn.net/educolumn/150d7073277950db5f09620704e791cf?spm=1055.2569.3001.10083)veSource TemplatedParent}}" ClickMode="Press"/> <ContentPresenter x:Name="ContentSite" IsHitTestVisible="False" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" Margin="3,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Left"/> <Popup x:Name="Popup" IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom" StaysOpen="False"> <Border x:Name="DropDownBorder" Background="White" BorderThickness="1" BorderBrush="LightGray"> <ScrollViewer> <ItemsControl x:Name="ItemsControl" ItemsSource="{TemplateBinding ItemsSource}" ItemTemplate="{TemplateBinding ItemTemplate}" SelectionMode="Multiple"/> </ScrollViewer> </Border> </Grid> </Popup> </Grid> <ControlTemplate.Triggers> <Trigger Property="HasItems" Value="False"> <Setter Property="Visibility" Value="Collapsed" TargetName="DropDownBorder"/> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Foreground" Value="Gray"/> </Trigger> <DataTrigger Binding="{Binding Path=Text.Length, RelativeSource={RelativeSource Self}}" Value="0"> <Setter Property="SelectedIndex" Value="-1" /> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </ComboBox.Template> </ComboBox>