WPF开发中遇到的新知识 -- 7
搜索框
目的:希望一个类似百度搜索框的功能,在输入框中输入内容,弹出下拉框,下拉框的内容随着输入的变化而变化
方法:
- 输入框,用户在输入的时候,变化的是
Text
属性,我们可以先绑定一个属性在输入框的内容中,不过是单向绑定OneWay
,这样输入框的变化就不会影响到后台,那么搜索的内容如何获取呢?继续引入微软的behaviors
,然后当用户输入的时候,会不断触发输入框的TextChanged
事件,利用这个事件,绑定一个命令,将用户输入的内容传递到命令里面,这样我们就可以获取到输入的内容。而上面绑定的属性,是在用户选择了下拉框的完整内容后,填充输入框的,所以需要分开 - Popup,弹出框,容器,
- ListBox,承载搜索结果,数据来源会被输入框的命令所改变,用户点击选择的子项,会改变绑定在输入框
Text
上的属性,导致用户点击子项后,输入框的内容会变为点击的内容
<TextBox Grid.Column="0" x:Name="LineInputBox" Text="{Binding SearchLineItem,Mode=OneWay,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource lineConverter}}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction
Command="{Binding SearchLineCommand}"
CommandParameter="{Binding ElementName=LineInputBox,Path=Text}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
<Popup
Grid.Column="0"
IsOpen="{Binding ElementName=LineInputBox,Path=IsKeyboardFocused,Mode=OneWay}"
PlacementTarget="{Binding ElementName=LineInputBox}"
Placement="Bottom"
Width="{Binding ElementName=LineInputBox,Path=ActualWidth}"
AllowsTransparency="True"
PopupAnimation="Slide">
<ListBox
SelectedItem="{Binding SearchLineItem,Mode=OneWayToSource,UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding LineSourceDto,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource lineToNameConverter}">
<Binding Path="StartPoint"/>
<Binding Path="EndPoint"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Popup>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?