最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

WPF利用CommunityToolkit.Mvvm實現(xiàn)級聯(lián)選擇器

 更新時間:2023年12月25日 10:16:59   作者:WPF開發(fā)者  
這篇文章主要介紹了WPF如何利用CommunityToolkit.Mvvm實現(xiàn)級聯(lián)選擇器,文中的示例代碼講解詳細,對我們的學習或工作有一定幫助,需要的小伙伴可以參考一下

WPF 使用 CommunityToolkit.Mvvm 實現(xiàn)級聯(lián)選擇器

框架使用.NET5;

Visual Studio 2022;

示例代碼

1)CascadePicker.cs 代碼如下:

  • Text 獲取或設置級聯(lián)選擇器的文本值。
  • IsDropDownOpen 級聯(lián)選擇器的下拉菜單是否打開。
  • MaxDropDownHeight 級聯(lián)選擇器下拉菜單的最大高度。
  • OnApplyTemplate 重寫了基類的模板應用方法。
  • MenuItem_Click 菜單項點擊事件,根據(jù)用戶選擇的菜單項更新級聯(lián)選擇器的文本值,并關閉下拉菜單。
  • GetHierarchicalPath 菜單項的層次結構獲取完整的路徑字符串。
  • GetParentHierarchy 菜單項的父級層次結構。
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace WpfCascadePicker.Controls
{
    public class CascadePicker : MenuBase
    {
        private static readonly Type _typeofSelf = typeof(CascadePicker);
        static CascadePicker()
        {
            DefaultStyleKeyProperty.OverrideMetadata(_typeofSelf, new FrameworkPropertyMetadata(_typeofSelf));
        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(CascadePicker), new PropertyMetadata(string.Empty));



        public static readonly DependencyProperty IsDropDownOpenProperty = DependencyProperty.Register(
            "IsDropDownOpen", typeof(bool), typeof(CascadePicker), new PropertyMetadata(false));

        public bool IsDropDownOpen
        {
            get { return (bool)GetValue(IsDropDownOpenProperty); }
            set { SetValue(IsDropDownOpenProperty, value); }
        }

        public static readonly DependencyProperty MaxDropDownHeightProperty = DependencyProperty.Register(
            "MaxDropDownHeight", typeof(double), typeof(CascadePicker), new PropertyMetadata(SystemParameters.PrimaryScreenHeight / 3.0));
        public double MaxDropDownHeight
        {
            get
            {
                return (double)GetValue(MaxDropDownHeightProperty);
            }
            set
            {
                SetValue(MaxDropDownHeightProperty, value);
            }
        }
        
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
        }
        public CascadePicker()
        {
            AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(MenuItem_Click));
        }
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            var clickedMenuItem = e.OriginalSource as MenuItem;
            if (clickedMenuItem != null)
            {
                List<string> hierarchy = GetParentHierarchy(clickedMenuItem);
                Text = GetHierarchicalPath(hierarchy);
            }
            IsDropDownOpen = false;
        }
        private string GetHierarchicalPath(List<string> hierarchy)
        {
            hierarchy.Reverse();
            return string.Join(" / ", hierarchy);
        }
        private List<string> GetParentHierarchy(MenuItem item)
        {
            var hierarchy = new List<string>();

            var headerObject = item.Header;
            var propertyInfo = headerObject.GetType().GetProperty(DisplayMemberPath);
            if (propertyInfo != null)
            {
                var displayValue = propertyInfo.GetValue(headerObject, null) as string;
                if (!string.IsNullOrEmpty(displayValue))
                    hierarchy.Add(displayValue);
            }
            var parent = VisualTreeHelper.GetParent(item);
            if (parent != null)
            {
                var stackPanel = parent as StackPanel;
                if (stackPanel != null)
                {
                    var menuItemParent = stackPanel.TemplatedParent as MenuItem;
                    if (menuItemParent != null)
                    {
                        var parentHierarchy = GetParentHierarchy(menuItemParent);
                        hierarchy.AddRange(parentHierarchy);
                    }
                }
            }
            return hierarchy;
        }
    }
}

2)CascadePicker.xaml 代碼如下:

  • 子菜單項的樣式使用了WD.DefaultMenuItem樣式,并綁定了ItemsSource屬性。
  • 定義了控件的外觀和行為,包括邊框、文本框、下拉箭頭、下拉彈出窗口等元素。
  • 觸發(fā)器定義了控件的交互行為,例如鼠標懸停、下拉彈出窗口的打開和關閉等。
<Application
    x:Class="WpfCascade.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:WpfCascadePicker.Controls"
    xmlns:local="clr-namespace:WpfCascade"
    xmlns:wd="https://github.com/WPFDevelopersOrg/WPFDevelopers"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/WPFDevelopers;component/Themes/Light.Blue.xaml" />
                <!--  需要注意 wd:Resources 必須在配色主題后,Theme="Dark" 為黑色皮膚  -->
                <wd:Resources Theme="Light" />
                <ResourceDictionary Source="pack://application:,,,/WPFDevelopers;component/Themes/Theme.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <Style BasedOn="{StaticResource WD.ControlBasicStyle}" TargetType="{x:Type controls:CascadePicker}">
                <Setter Property="HorizontalContentAlignment" Value="Left" />
                <Setter Property="VerticalContentAlignment" Value="Center" />
                <Setter Property="BorderBrush" Value="{DynamicResource WD.BaseSolidColorBrush}" />
                <Setter Property="BorderThickness" Value="1" />
                <Setter Property="Background" Value="{DynamicResource WD.BackgroundSolidColorBrush}" />
                <Setter Property="Padding" Value="{StaticResource WD.DefaultPadding}" />
                <Setter Property="ItemContainerStyle">
                    <Setter.Value>
                        <Style BasedOn="{StaticResource WD.DefaultMenuItem}" TargetType="MenuItem">
                            <Setter Property="ItemsSource" Value="{Binding ItemsSource}" />
                            <Setter Property="ItemContainerStyle">
                                <Setter.Value>
                                    <Style BasedOn="{StaticResource WD.DefaultMenuItem}" TargetType="MenuItem">
                                        <Setter Property="ItemsSource" Value="{Binding ItemsSource}" />
                                    </Style>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Setter.Value>
                </Setter>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type controls:CascadePicker}">
                            <ControlTemplate.Resources>
                                <Storyboard x:Key="OpenStoryboard">
                                    <DoubleAnimation
                                        EasingFunction="{StaticResource WD.ExponentialEaseOut}"
                                        Storyboard.TargetName="PART_DropDown"
                                        Storyboard.TargetProperty="(Grid.RenderTransform).(ScaleTransform.ScaleY)"
                                        To="1"
                                        Duration="00:00:.2" />
                                </Storyboard>
                                <Storyboard x:Key="CloseStoryboard">
                                    <DoubleAnimation
                                        EasingFunction="{StaticResource WD.ExponentialEaseOut}"
                                        Storyboard.TargetName="PART_DropDown"
                                        Storyboard.TargetProperty="(Grid.RenderTransform).(ScaleTransform.ScaleY)"
                                        To="0"
                                        Duration="00:00:.2" />
                                </Storyboard>
                            </ControlTemplate.Resources>
                            <wd:SmallPanel SnapsToDevicePixels="True">
                                <Border
                                    Name="PART_Border"
                                    Background="{TemplateBinding Background}"
                                    BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="{TemplateBinding BorderThickness}"
                                    CornerRadius="{Binding Path=(wd:ElementHelper.CornerRadius), RelativeSource={RelativeSource TemplatedParent}}"
                                    SnapsToDevicePixels="True" />
                                <TextBox
                                    Name="PART_EditableTextBox"
                                    Margin="{TemplateBinding Padding}"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                    Background="{TemplateBinding Background}"
                                    Focusable="True"
                                    Foreground="{DynamicResource WD.PrimaryTextSolidColorBrush}"
                                    IsReadOnly="True"
                                    SelectionBrush="{DynamicResource WD.WindowBorderBrushSolidColorBrush}"
                                    Style="{x:Null}"
                                    Template="{StaticResource WD.ComboBoxTextBox}"
                                    Text="{Binding Text, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" />
                                <TextBlock
                                    Name="PART_Watermark"
                                    Margin="{TemplateBinding Padding}"
                                    Padding="1,0"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                    Background="Transparent"
                                    Foreground="{DynamicResource WD.RegularTextSolidColorBrush}"
                                    IsHitTestVisible="False"
                                    Text="{Binding Path=(wd:ElementHelper.Watermark), RelativeSource={RelativeSource TemplatedParent}}"
                                    TextBlock.FontSize="{StaticResource WD.NormalFontSize}"
                                    TextTrimming="CharacterEllipsis"
                                    Visibility="Collapsed" />
                                <ToggleButton
                                    Name="PART_ToggleButton"
                                    Background="{TemplateBinding Background}"
                                    ClickMode="Release"
                                    Focusable="False"
                                    IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                    Style="{x:Null}"
                                    Template="{StaticResource WD.ComboBoxToggleButton}" />
                                <Popup
                                    Name="PART_Popup"
                                    AllowsTransparency="True"
                                    IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
                                    Placement="Bottom"
                                    PlacementTarget="{Binding ElementName=PART_ToggleButton}"
                                    StaysOpen="False">
                                    <wd:SmallPanel
                                        Name="PART_DropDown"
                                        MinWidth="{TemplateBinding FrameworkElement.ActualWidth}"
                                        MaxHeight="{TemplateBinding MaxDropDownHeight}"
                                        Margin="24,2,24,24"
                                        RenderTransformOrigin=".5,0"
                                        SnapsToDevicePixels="True">
                                        <wd:SmallPanel.RenderTransform>
                                            <ScaleTransform ScaleY="0" />
                                        </wd:SmallPanel.RenderTransform>
                                        <Border
                                            Name="PART_DropDownBorder"
                                            Background="{TemplateBinding Background}"
                                            BorderBrush="{TemplateBinding BorderBrush}"
                                            BorderThickness="{TemplateBinding BorderThickness}"
                                            CornerRadius="{Binding Path=(wd:ElementHelper.CornerRadius), RelativeSource={RelativeSource TemplatedParent}}"
                                            Effect="{StaticResource WD.PopupShadowDepth}"
                                            SnapsToDevicePixels="True"
                                            UseLayoutRounding="True">
                                            <ItemsPresenter />
                                        </Border>
                                    </wd:SmallPanel>
                                </Popup>
                            </wd:SmallPanel>
                            <ControlTemplate.Triggers>
                                <Trigger SourceName="PART_ToggleButton" Property="IsChecked" Value="True">
                                    <Trigger.EnterActions>
                                        <BeginStoryboard x:Name="BeginStoryboardOpenStoryboard" Storyboard="{StaticResource OpenStoryboard}" />
                                    </Trigger.EnterActions>
                                    <Trigger.ExitActions>
                                        <StopStoryboard BeginStoryboardName="BeginStoryboardOpenStoryboard" />
                                    </Trigger.ExitActions>
                                </Trigger>
                                <Trigger SourceName="PART_ToggleButton" Property="IsChecked" Value="False">
                                    <Trigger.EnterActions>
                                        <BeginStoryboard x:Name="BeginStoryboardCloseStoryboard" Storyboard="{StaticResource CloseStoryboard}" />
                                    </Trigger.EnterActions>
                                    <Trigger.ExitActions>
                                        <StopStoryboard BeginStoryboardName="BeginStoryboardCloseStoryboard" />
                                    </Trigger.ExitActions>
                                </Trigger>
                                <Trigger Property="UIElement.IsMouseOver" Value="True">
                                    <Setter TargetName="PART_Border" Property="BorderBrush" Value="{DynamicResource WD.PrimaryNormalSolidColorBrush}" />
                                </Trigger>
                                <Trigger SourceName="PART_EditableTextBox" Property="Text" Value="">
                                    <Setter TargetName="PART_Watermark" Property="Visibility" Value="Visible" />
                                </Trigger>
                                <Trigger SourceName="PART_EditableTextBox" Property="Text" Value="{x:Null}">
                                    <Setter TargetName="PART_Watermark" Property="Visibility" Value="Visible" />
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

3)CascadePickerExample.xaml 示例代碼如下:

 <controls:CascadePicker
            Width="240"
            Height="40"
            wd:ElementHelper.Watermark="請選擇內(nèi)容"
            DisplayMemberPath="Name"
            Text="{Binding City, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
            ItemsSource="{Binding CityInfos}" />

效果圖

以上就是WPF利用CommunityToolkit.Mvvm實現(xiàn)級聯(lián)選擇器的詳細內(nèi)容,更多關于WPF級聯(lián)選擇器的資料請關注腳本之家其它相關文章!

相關文章

  • C#中如何使用 XmlReader 讀取XML文件

    C#中如何使用 XmlReader 讀取XML文件

    本文介紹了C#中使用XmlReader,只讀、向前、循環(huán)讀取XML節(jié)點的方法,并為我們列出、XmlReader類的方法、屬性、枚舉等成員,希望對大家學習有所幫助。
    2016-05-05
  • c#將不同類型的數(shù)據(jù)存儲到一起的實現(xiàn)

    c#將不同類型的數(shù)據(jù)存儲到一起的實現(xiàn)

    在C#中存儲不同類型的數(shù)據(jù)有多種方式,本文主要介紹了c#將不同類型的數(shù)據(jù)存儲到一起的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2025-07-07
  • 使用C#代碼在PDF文檔中添加、刪除和替換圖片

    使用C#代碼在PDF文檔中添加、刪除和替換圖片

    在當今數(shù)字化文檔處理場景中,動態(tài)操作PDF文檔中的圖像已成為企業(yè)級應用開發(fā)的核心需求之一,本文 將介紹如何在.NET平臺使用C#代碼在PDF文檔中添加、刪除和替換圖片,需要的朋友可以參考下
    2025-04-04
  • C# 7.2中結構體性能問題的解決方案

    C# 7.2中結構體性能問題的解決方案

    這篇文章主要給大家介紹了關于C# 7.2中結構體性能問題的解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2018-08-08
  • 解析C#網(wǎng)絡編程中的Http請求

    解析C#網(wǎng)絡編程中的Http請求

    這篇文章主要介紹了C#網(wǎng)絡編程中的Http請求,不過這次也使我對C#網(wǎng)絡編程了解的更多,算是一次學習經(jīng)歷吧,文章結合示例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2022-03-03
  • C#中接口(interface)的理解

    C#中接口(interface)的理解

    C#中接口(interface)的理解...
    2007-03-03
  • 淺談C#泛型的用處與特點

    淺談C#泛型的用處與特點

    泛型是 2.0 版 C# 語言和公共語言運行庫 (CLR) 中的一個新功能。泛型將類型參數(shù)的概念引入 .NET Framework,類型參數(shù)使得設計如下類和方法成為可能:這些類和方法將一個或多個類型的指定推遲到客戶端代碼聲明并實例化該類或方法的時候
    2013-09-09
  • C#程序連接數(shù)據(jù)庫及讀取數(shù)據(jù)庫中字段的簡單方法總結

    C#程序連接數(shù)據(jù)庫及讀取數(shù)據(jù)庫中字段的簡單方法總結

    包括C#連接Access、Oracle或者SQL Server,這里整理了一些C#連接數(shù)據(jù)庫及從讀取數(shù)據(jù)庫中字段的簡單方法總結,需要的朋友可以參考下
    2016-05-05
  • C#如何添加PPT背景

    C#如何添加PPT背景

    這篇文章主要為大家詳細介紹了C#如何添加PPT背景,添加純色背景、漸變色背景、圖片背景等,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • c#中string的特性介紹及注意事項小結

    c#中string的特性介紹及注意事項小結

    這篇文章主要給大家介紹了關于c#中string的特性介紹及注意事項的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用c#具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-11-11

最新評論

宿迁市| 鸡泽县| 龙口市| 天气| 游戏| 汶川县| 汶川县| 清流县| 张家口市| 巩义市| 松原市| 县级市| 陆丰市| 即墨市| 衡水市| 阳江市| 西贡区| 泗水县| 娱乐| 诏安县| 汕头市| 兴安盟| 慈利县| 新巴尔虎左旗| 登封市| 蒲城县| 察隅县| 齐河县| 柘城县| 宜都市| 万州区| 怀远县| 宁武县| 南京市| 南汇区| 奉节县| 炉霍县| 湛江市| 大城县| 涟源市| 象山县|