文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

基于WPF怎么实现简单的下拉筛选控件

2023-07-05 23:17

关注

本文小编为大家详细介绍“基于WPF怎么实现简单的下拉筛选控件”,内容详细,步骤清晰,细节处理妥当,希望这篇“基于WPF怎么实现简单的下拉筛选控件”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

WPF 简单实现下拉筛选控件

框架使用.NET40

Visual Studio 2022;

使用 ICollectionView[2] 实现筛选功能,还支持其他如下:

基于WPF怎么实现简单的下拉筛选控件

实现代码

1)CheckedSearch.cs 代码如下:

using System.Collections.ObjectModel;using System.ComponentModel;using System.Linq;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using WpfCustomControlLibrary1.Datas;namespace WpfCustomControlLibrary1{    public class CheckedSearch : Control    {        private ICollectionView _filteredCollection;        public ICollectionView FilteredCollection { get { return _filteredCollection; } }        private string _searchText = string.Empty;        public string SearchText        {            get { return _searchText; }            set            {                if (_searchText != value)                {                    _searchText = value;                    _filteredCollection.Refresh();                }            }        }        public string Text        {            get { return (string)GetValue(TextProperty); }            set { SetValue(TextProperty, value); }        }        public static readonly DependencyProperty TextProperty =            DependencyProperty.Register("Text", typeof(string), typeof(CheckedSearch), new PropertyMetadata(string.Empty));        public ObservableCollection<CheckedSearchItem> ItemsSource        {            get { return (ObservableCollection<CheckedSearchItem>)GetValue(ItemsSourceProperty); }            set { SetValue(ItemsSourceProperty, value); }        }        public static readonly DependencyProperty ItemsSourceProperty =            DependencyProperty.Register("ItemsSource", typeof(ObservableCollection<CheckedSearchItem>), typeof(CheckedSearch), new PropertyMetadata(null, OnItemsSourceChanged));        private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)        {            var choseSearch = (CheckedSearch)d;            if (choseSearch == null) return;            if (choseSearch._filteredCollection == null && choseSearch.ItemsSource.Count > 0)            {                foreach (var item in choseSearch.ItemsSource)                {                    item.PropertyChanged -= choseSearch.Item_PropertyChanged;                    item.PropertyChanged += choseSearch.Item_PropertyChanged;                }                choseSearch._filteredCollection = CollectionViewSource.GetDefaultView(choseSearch.ItemsSource);                choseSearch._filteredCollection.Filter = choseSearch.ContainsFilter;            }        }        string GetItems()        {            var list = ItemsSource.Where(x=>x.IsChecked).Select(x=>x.Name).ToList();            var visibleItems = string.Join("^",list);            return visibleItems;        }        static CheckedSearch()        {            DefaultStyleKeyProperty.OverrideMetadata(typeof(CheckedSearch), new FrameworkPropertyMetadata(typeof(CheckedSearch)));        }        private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)        {            if (e.PropertyName == "IsChecked")                Text = GetItems();                    }        private bool ContainsFilter(object item)        {            var model = item as CheckedSearchItem;            if (model == null)                return false;            if (string.IsNullOrEmpty(SearchText))                return true;            if (model.Name.ToUpperInvariant().Contains(SearchText.ToUpperInvariant()))                return true;            return false;        }    }}

2)CheckedSearchItem.cs 代码如下:

using System.ComponentModel;namespace WpfCustomControlLibrary1.Datas{    public class CheckedSearchItem    {        public string Name { get; set; }        private bool _isChecked;        public bool IsChecked        {            get { return _isChecked; }            set            {                _isChecked = value;                OnPropertyChanged("IsChecked");            }        }                public event PropertyChangedEventHandler PropertyChanged;        protected void OnPropertyChanged(string propertyName)        {            if (PropertyChanged != null)                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));        }    }}

3)CheckedSearch.xaml 代码如下:

<Style TargetType="{x:Type local:CheckedSearch}">        <Setter Property="Height" Value="40"/>        <Setter Property="Width" Value="200"/>        <Setter Property="BorderBrush" Value="DodgerBlue"/>        <Setter Property="Background" Value="White"/>        <Setter Property="BorderThickness" Value="1"/>        <Setter Property="Template">            <Setter.Value>                <ControlTemplate TargetType="{x:Type local:CheckedSearch}">                    <Border Background="{TemplateBinding Background}"                            BorderBrush="{TemplateBinding BorderBrush}"                            BorderThickness="{TemplateBinding BorderThickness}"                            x:Name="PART_Border">                        <Grid>                            <Grid.ColumnDefinitions>                                <ColumnDefinition/>                                <ColumnDefinition Width="Auto"/>                            </Grid.ColumnDefinitions>                            <TextBlock Text="{Binding Text,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"                                       Foreground="Black"                                       VerticalAlignment="Center"                                       Margin="2,0"/>                            <ToggleButton x:Name="PART_ToggleButton"            Focusable="False"                                      Width="30"                                      Style="{x:Null}"                                      Grid.Column="1"           ClickMode="Release">                                <Path Stretch="Fill"                                       Height="6" Width="10"                                        HorizontalAlignment="Center"                                       VerticalAlignment="Center"                   Data="M998 352c0 -8 -4 -17 -10 -23l-50 -50c-6 -6 -14 -10 -23 -10c-8 0 -17 4 -23 10l-393 393l-393 -393c-6 -6 -15 -10 -23 -10s-17 4 -23 10l-50 50c-6 6 -10 15 -10 23s4 17 10 23l466 466c6 6 15 10 23 10s17 -4 23 -10l466 -466c6 -6 10 -15 10 -23z"                                       Fill="Black">                                </Path>                            </ToggleButton>                            <Popup IsOpen="{Binding ElementName=PART_ToggleButton,Path=IsChecked}"                                   x:Name="PART_Popup"                                   VerticalOffset="2"                                   AllowsTransparency="True"        PlacementTarget="{Binding ElementName=PART_Border}"        Placement="Bottom" StaysOpen="False">                                <Border Width="{TemplateBinding Width}"                                        Padding="2,4"                                        Background="{TemplateBinding Background}"                            BorderBrush="{TemplateBinding BorderBrush}"                            BorderThickness="{TemplateBinding BorderThickness}">                                    <StackPanel>                                        <TextBox Text="{Binding SearchText,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"                                                 Height="40" VerticalContentAlignment="Center"                                                 Margin="0,0,0,2"/>                                        <ListBox ItemsSource="{TemplateBinding ItemsSource}">                                            <ListBox.ItemTemplate>                                                <DataTemplate>                                                    <CheckBox Content="{Binding Name}"                                                               IsChecked="{Binding IsChecked}"/>                                                </DataTemplate>                                            </ListBox.ItemTemplate>                                        </ListBox>                                    </StackPanel>                                </Border>                                                            </Popup>                        </Grid>                    </Border>                </ControlTemplate>            </Setter.Value>        </Setter>    </Style>

4)CheckedSearchExample.xaml 示例代码如下:

<wd:Window x:Class="WpfApp1.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"        xmlns:wd="https://github.com/WPFDevelopersOrg/WPFDevelopers"        xmlns:custom="clr-namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1"        xmlns:local="clr-namespace:WpfApp1"        mc:Ignorable="d"         Title="WPFDevelopers - 搜索多选控件" Height="450" Width="800">   <Window.Resources>        <ResourceDictionary>            <ResourceDictionary.MergedDictionaries>                <ResourceDictionary Source="pack://application:,,,/WpfApp1;component/CheckedSearch.xaml"/>            </ResourceDictionary.MergedDictionaries>        </ResourceDictionary>    </Window.Resources>  <!--公众号:WPF开发者-->    <Grid>        <custom:CheckedSearch             ItemsSource="{Binding ItemsSource,RelativeSource={RelativeSource AncestorType=Window}}"            VerticalAlignment="Top" Margin="0,10"/>    </Grid></wd:Window>

5)CheckedSearchExample.xaml 数据源示例代码如下:

using System.Collections.ObjectModel;using System.Windows;using WpfCustomControlLibrary1.Datas;namespace WpfApp1{    public partial class MainWindow    {        public ObservableCollection<CheckedSearchItem> ItemsSource        {            get { return (ObservableCollection<CheckedSearchItem>)GetValue(ItemsSourceProperty); }            set { SetValue(ItemsSourceProperty, value); }        }        public static readonly DependencyProperty ItemsSourceProperty =            DependencyProperty.Register("ItemsSource", typeof(ObservableCollection<CheckedSearchItem>), typeof(MainWindow), new PropertyMetadata(null));        public MainWindow()        {            InitializeComponent();            Loaded += MainWindow_Loaded;        }        private void MainWindow_Loaded(object sender, RoutedEventArgs e)        {            ItemsSource = new ObservableCollection<CheckedSearchItem>();            var items = new ObservableCollection<CheckedSearchItem>();            items.Add(new CheckedSearchItem { Name = "Winform" });            items.Add(new CheckedSearchItem { Name = "WPF" });            items.Add(new CheckedSearchItem { Name = "WinUI 3" });            items.Add(new CheckedSearchItem { Name = "MAUI" });            items.Add(new CheckedSearchItem { Name = "Avalonia UI" });            ItemsSource = items;        }    }}

读到这里,这篇“基于WPF怎么实现简单的下拉筛选控件”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注编程网行业资讯频道。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯