【WPF】ComboBox控件

ComboBox控件属性

IsTextSearchEnabled="True":自动补充数据

IsTextSearchCaseSensitive = true;自动补充数据,区分大小写

IsDropDownOpen="True":combobox  下拉框开关

IsEditable就是启用或禁用 ComboBox 的文本框中的文本编辑,让combobox可以输入内容

IsTextSearchEnabled="False"支持下拉列表的搜索过滤功能

SelectedIndex = 0;//设置默认显示的item索引

 MaxDropDownHeight="250"  最大下拉框高度,无法显示的的部分,会出现滚动条。

 SelectedItem属性返回列表绑定到Item的整个对象。

SelectedValuePath(model中属性)、SelectedValue(Viewmodel中属性)连个是配套使用的。这两者是讲model中的属性和viewmodel中的属性关联起来。

ComboBox附加事件

<ComBox Width="100" Name="SFRName" IsEditable="True"  IsTextSearchEnabled = "true" TextBoxBase.TextChanged="SFRName_TextChanged"/>

当IsEditable设置为true时,ComboBox使用TextBox来显示和编辑文本。 TextBox的TextChanged事件是一个冒泡事件-表示它将在元素树中冒泡,因此我们可以在ComboBox本身上进行处理。
ComboBox本身不公开TextChanged事件,可以使用附加事件为其定义处理程序,因此,使用TextBoxBase.TextChanged语法.
另外IsTextSearchEnabled属性可以实现查询.

combobox 输入内容自动打开下拉列表框

popup StaysOpen="False"

 

TextSearch 类

使用户能够通过键入字符串的前缀来快速访问组中的项。

示例

以下示例创建 ComboBox 包含图像(而不是文本)的控件。 在功能上,示例是相同的。 第一个示例设置 TextPath 集合中 ComboBox 每个项的属性,第二个示例设置 Text 集合中每个项的属性

<ComboBox IsEditable="true" TextSearch.TextPath="Name">
  <Image Name="Cat" Source="data\cat.png"/>
  <Image Name="Dog" Source="data\dog.png"/>
  <Image Name="Fish" Source="data\fish.png"/>
</ComboBox>

 

 

其他知识点

BitmapImage 是位图,主要用于支持可扩展应用程序标记语言 (XAML) 语法

给下拉框添加阴影效果

引入命名空间:xmlns:theme="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero2"

给控件添加引用,这个性能比较好。

例如给Combobox下拉框添加引用效果

 阴影样式一

<--! 其他代码-->
  <Popup x:Name="PART_Popup" AllowsTransparency="true" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}" Placement="Bottom" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}">
                <theme:SystemDropShadowChrome x:Name="shadow"
                                              Color="Transparent"
                                              RenderTransformOrigin ="5,5"
                                              CornerRadius="4"
                                              MinWidth="{Binding ActualWidth, ElementName=templateRoot}"
                                              MaxHeight="{TemplateBinding MaxDropDownHeight}">
<--!      Margin="10,10,0,0" 这个是重点,显示左边和上边的阴影,默认左下角就有阴影-->
                    <Border x:Name="dropDownBorder"  
                            Margin="10,10,0,0"
                             CornerRadius="4"
                            Padding="10"
                            Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
                            BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}"  >
                      
                        <ScrollViewer x:Name="DropDownScrollViewer">
                            <Grid x:Name="grid" RenderOptions.ClearTypeHint="Enabled">
                                <Canvas x:Name="canvas" HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                    <Rectangle x:Name="opaqueRect" Fill="{Binding Background, ElementName=dropDownBorder}" Height="{Binding ActualHeight, ElementName=dropDownBorder}" Width="{Binding ActualWidth, ElementName=dropDownBorder}"/>
                                </Canvas>
                                <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            </Grid>
                        </ScrollViewer>
                    </Border>
                </theme:SystemDropShadowChrome>
            </Popup>
<--! 其他代码-->

效果如下:

 阴影样式二

Margin="8,8,-2,-2" 这个是重点 控制阴影,显示左边和上边的阴影,调整左下角的阴影。
<--! 其他代码-->
  <Popup x:Name="PART_Popup" AllowsTransparency="true" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}" Placement="Bottom" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}">
                <theme:SystemDropShadowChrome x:Name="shadow"
                                              Color="Transparent"
                                              RenderTransformOrigin ="5,5"
                                              CornerRadius="4"
                                              MinWidth="{Binding ActualWidth, ElementName=templateRoot}"
                                              MaxHeight="{TemplateBinding MaxDropDownHeight}">
<--!       Margin="8,8,-2,-2" 这个是重点 控制阴影,显示左边和上边的阴影,调整左下角的阴影-->
                    <Border x:Name="dropDownBorder"  
                              Margin="8,8,-2,-2"
                             CornerRadius="4"
                            Padding="10"
                            Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
                            BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}"  >
                      
                        <ScrollViewer x:Name="DropDownScrollViewer">
                            <Grid x:Name="grid" RenderOptions.ClearTypeHint="Enabled">
                                <Canvas x:Name="canvas" HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                    <Rectangle x:Name="opaqueRect" Fill="{Binding Background, ElementName=dropDownBorder}" Height="{Binding ActualHeight, ElementName=dropDownBorder}" Width="{Binding ActualWidth, ElementName=dropDownBorder}"/>
                                </Canvas>
                                <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            </Grid>
                        </ScrollViewer>
                    </Border>
                </theme:SystemDropShadowChrome>
            </Popup>
<--! 其他代码-->

 

功能应用

(1)绑定SelectedItem

可以通过selecteditem的变更跟新信息。

viewmodel

        public UserInfoViewModel SelectedItem
        {
            get { return selectedItem; }
            set {
                SetProperty(ref selectedItem, value);

                if (value!=null)
                {
                   //更新用户头像
                    userInfo.Photo = value.UserInfoClone.Photo;
                    OnPropertyChanged("UserImage");
                    //更新用户名
                    UserName = value.UserInfoClone.Name;
                    OnPropertyChanged("UserName");

                    //更新记住密码
                    IsRememberPassword = value.UserInfoClone.IsRememberPassword;

                }
                else
                {
                   
                            //选择项目为空,则删除已经选择的项,清空用户头像、记住密码
                          
                             IsRememberPassword = false;
                             userInfo.Photo = null;
                             OnPropertyChanged("UserImage");//之所有这样写是因为 userInfo.Photo 

                             return; 

                        return;
                    
                }

            }
        }

view

            <ComboBox Style="{DynamicResource ComboBoxStyle1}"
                      Name="uerlist" Height="30" 
                      BorderThickness="0,0,0,1" 
                      ItemsSource="{Binding UserInfoList}" 
                      IsEditable="True" 
                     SelectedItem="{Binding SelectedItem}"
                      MaxDropDownHeight="250"
                      VerticalContentAlignment="Center"  
                      Padding="10,0,0,0"  IsTextSearchEnabled="True"  
                   
                    
                      Margin="20,0,20,10" >

 (2)SelectedValuePath 、SelectedValue

SelectedValuePath(model中属性)、SelectedValue(Viewmodel中属性)连个是配套使用的。这两者是讲model中的属性和viewmodel中的属性关联起来。

View

<ComboBox Margin="-16,3,0,5" Grid.Row="1" Grid.Column="2" Grid.ColumnSpan="2" Name="cboxLocationKeyword"
 ItemsSource="{Binding LocationSource,Mode=OneWay}"
 SelectedValuePath="ID"
 DisplayMemberPath="Info"
 SelectedItem="{Binding SelectLocation}" />

ViewModel

public class LocationRoad
{
    public int ID { set; get; }
    public string Code { set; get; }
    public string Info { set; get; }
}
//
/// 当ComboBox选中项更改时发生
///
private LocationRoad _selectLocation;
public LocationRoad SelectLocation
{
    get
    {
        return this._selectLocation;
    }
    set
    {
        this._selectLocation = value;
        if (this.PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("SelectLocation"));
    }
}
 
private ObservableCollection _locationRoad = null;
 
public ObservableCollection LocationSource
{
    get
    {
        if (this._locationRoad == null)
        {
            this._locationRoad = new ObservableCollection() {
                 new LocationRoad() { ID = 1, Code = "NGQ", Info = "南岗区" },
                 new LocationRoad() { ID = 2, Code = "DLQ", Info = "道里区" },
                 new LocationRoad() { ID = 3, Code = "DWQ", Info = "道外区" },
                 new LocationRoad() { ID = 4, Code = "PFQ", Info = "平房区" },
                 new LocationRoad() { ID = 5, Code = "XFQ", Info = "香坊区" },
                 };
 
        }
        return this._locationRoad;
    }
    set
    {
        this._locationRoad = value;
        if (this.PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("LocationSource"));
    }
}

 (3)Combobox 下拉项 切换

下面是下拉框的重点代码,其他代码没列出。

view

<Window x:Class="LYFWPFUI.MVVM.Views.LoginView"
        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:cus="clr-namespace:LYFWPFUI.Theme.CustomeControls"
        xmlns:local="clr-namespace:LYFWPFUI.MVVM.Views"
        xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
        mc:Ignorable="d"
        Background="{x:Null}"
         
        WindowStartupLocation="CenterScreen"
        WindowStyle="None"
        AllowsTransparency="True"
        MinHeight="460"
        MinWidth="340"
        MaxWidth="280"
        MaxHeight="380"
       Style="{StaticResource RegisterWindowStyle}"
        Title="登入" Height="380" Width="280">
    <Window.Resources>
        <ControlTemplate x:Key="displayErrorMsgFomatte">
            <StackPanel>
                <!-- Placeholder for the TextBox itself -->
                <AdornedElementPlaceholder x:Name="textBox"/>
                <ItemsControl ItemsSource="{Binding}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding ErrorContent}" Foreground="Red"/>

                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </ControlTemplate>

    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <Border Margin="20,20,20,20" Width="100" Height="100" Grid.Row="0" BorderThickness="1"  CornerRadius="50" ClipToBounds="True"    BorderBrush="#c5a6c8">
            <Border.Background>
                <ImageBrush ImageSource="{Binding  UserImage}"/>
            </Border.Background>


        </Border>
        <StackPanel Grid.Row="1" Margin="20,20,20,0" Background="White">

            <ComboBox Style="{DynamicResource ComboBoxStyle1}"
                      Name="uerlist" Height="30" 
                      BorderThickness="0,0,0,1" 
                      ItemsSource="{Binding UserInfoList}" 
                      SelectedValue="{Binding UserName}"
                      SelectedValuePath="UserName"
                      IsEditable="True" 
                      SelectedItem="{Binding SelectedItem}"
                      MaxDropDownHeight="250"
                      VerticalContentAlignment="Center"  
                      Text="{Binding UserName}"
                      Padding="10,0,0,0"  IsTextSearchEnabled="True"  
                   
                    
                      Margin="20,0,20,10" >
                <ComboBox.ItemTemplate>
                    <DataTemplate >
                        <Grid HorizontalAlignment="Stretch">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="45"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="40"/>
                            </Grid.ColumnDefinitions>


                            <Border VerticalAlignment="Center" HorizontalAlignment="Left" Margin="0,0,10,0" Grid.Column="0" BorderThickness="1" Width="35" Height="35" CornerRadius="20" BorderBrush="#c5a6c8">
                                <Border.Background>
                                    <ImageBrush ImageSource="{Binding UserImage}"/>
                                </Border.Background>
                            </Border>
                            <TextBlock  HorizontalAlignment="Stretch"  Text="{Binding UserName}" VerticalAlignment="Center" Grid.Column="1"></TextBlock>


                            <Button HorizontalAlignment="Stretch"
                                    VerticalAlignment="Stretch"
                                    x:Name="closebtn"
                                    Width="30"
                                    Command="{Binding ClearLocalLoginRecordCommand}"
                                    Grid.Column="2"
                                    Height="30"
                                    ToolTip="删除本地登入记录"
                                    Style="{DynamicResource  DeleteButtonStyle}" 
                                    Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"  >


                            </Button>

                        </Grid>
                    </DataTemplate>
                </ComboBox.ItemTemplate>

                <b:Interaction.Triggers>
                    <b:EventTrigger EventName="SelectionChanged">
                        <b:InvokeCommandAction Command="{Binding UpdataCommand}"   >
                            <b:InvokeCommandAction.CommandParameter>
                                <MultiBinding Converter="{StaticResource MultiBindingConverter}">
                                    <Binding ElementName="password"/>
                                    <Binding ElementName="uerlist"/>
                                </MultiBinding>
                            </b:InvokeCommandAction.CommandParameter>
                        </b:InvokeCommandAction>
                    </b:EventTrigger>
                </b:Interaction.Triggers>

            </ComboBox>

            <cus:PasswordBoxBingable  Height="30" 
                                     x:Name="password"
                                      VerticalAlignment="Stretch"
                                     Password="{Binding Password,Mode=TwoWay}"  
                                     VerticalContentAlignment="Stretch"
                            
                                     Foreground="Black" 
                                     Hint="请输入密码" 
                                     Validation.ErrorTemplate="{StaticResource  displayErrorMsgFomatte}"
                                     Margin="20,40,20,10"></cus:PasswordBoxBingable>

            <TextBlock Margin="20,0,20,5" Foreground="Red" Text="{Binding ErrorMessage}"></TextBlock>
            <Grid Margin="20,0" Height="40">
                <CheckBox VerticalAlignment="Center"  IsChecked="{Binding  IsRememberPassword}">记住密码</CheckBox>
                <Button   Background="#1ed3ac"  
                          FontWeight="Bold" 
                          Foreground="White" 
                          Cursor="Hand" 
                          Width="80"
                          Height="38"
                          Command="{Binding LoginCommand}" 
                          HorizontalAlignment="Right" 
                            >登入
                    <Button.Style>
                        <Style TargetType="{x:Type Button}">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type Button}">
                                        <Border  Padding="{TemplateBinding Padding}"
                                                 Name="border" Width="{TemplateBinding Width}"
                                                 Background="{TemplateBinding Background}" 
                                                 BorderBrush="#1ed3ac" 
                                                 BorderThickness="1" 
                                                 CornerRadius="4">

                                            <TextBlock  Name="txt" VerticalAlignment="Center"  HorizontalAlignment="Center">登入</TextBlock>
                                        </Border>
                                        <ControlTemplate.Triggers>
                                            <Trigger  Property="IsPressed" Value="true">
                                                <Setter TargetName="txt" Property="Padding"  Value="2,2,0,0"/>
                                            </Trigger>
                                        </ControlTemplate.Triggers>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>

                    </Button.Style>
                </Button>
            </Grid>

        </StackPanel>
        <WrapPanel Margin="20,0"  Grid.Row="2" >
            <Button Grid.Row="2"   
                    Height="60"
                    Width="90"
                    Padding="20,10" HorizontalAlignment="Left"   Command="{Binding NewRegisterCommand}" Cursor="Hand" Background="Transparent" BorderThickness="0">
                <Button.Style x:Uid="dd">
                    <Style TargetType="{x:Type Button}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type Button}">
                                    <Border Name="border" Padding="{TemplateBinding Padding}" Width="{TemplateBinding Width}" Background="{TemplateBinding Background}" BorderBrush="#1ed3ac" VerticalAlignment="{TemplateBinding VerticalAlignment}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4">
                                        <TextBlock  x:Name="txt" VerticalAlignment="Center"  HorizontalAlignment="Center">注册账户</TextBlock>
                                    </Border>
                                    <ControlTemplate.Triggers>
                                        <Trigger Property="IsPressed" Value="true">
                                            <Setter TargetName="txt" Property="Margin"  Value="2,2,0,0"/>
                                        </Trigger>
                                    </ControlTemplate.Triggers>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>

                </Button.Style>
                注册账户
            </Button>
            <Button Grid.Row="2"
                Padding="20,0"
                Height="60"
                Width="90"
                HorizontalAlignment="Left" 
                Command="{Binding NewRegisterCommand}"
                Cursor="Hand" 
                Background="Transparent" 
                BorderThickness="0">

                <Button.Style x:Uid="dd">
                    <Style TargetType="{x:Type Button}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type Button}">
                                    <Border Name="border" Padding="{TemplateBinding Padding}" 
                                        Width="{TemplateBinding Width}" 
                                        Background="{TemplateBinding Background}"
                                        BorderBrush="#1ed3ac"
                                        VerticalAlignment="{TemplateBinding VerticalAlignment}" 
                                        BorderThickness="{TemplateBinding BorderThickness}"
                                        CornerRadius="4">
                                        <TextBlock x:Name="txt"   VerticalAlignment="Center"  HorizontalAlignment="Center"> 找回密码</TextBlock>
                                    </Border>
                                    <ControlTemplate.Triggers>
                                        <Trigger Property="IsPressed" Value="true">

                                            <Setter TargetName="txt" Property="Margin"  Value="2,2,0,0"/>
                                        </Trigger>
                                    </ControlTemplate.Triggers>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>

                </Button.Style>
                注册账户
            </Button>
        </WrapPanel>
    </Grid>
</Window>

 

viewmodel

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LinMVVMTools.ViewModel;
using LYFWPFUI.Command;
using LYFWPFUI.Help;
using LYFWPFUI.MVVM.Models;
using LYFWPFUI.MVVM.Views;
using LYFWPFUI.Repositories;
using LYFWPFUI.Theme.CustomeControls;
using Microsoft.Extensions.DependencyInjection;


namespace LYFWPFUI.MVVM.ViewModels
{
    internal sealed partial class LoginViewModel : ViewModelBaseN
    {
        //构造函数
        public LoginViewModel()
        {

            macloaction = ComputerInfo.DiskID;//获取硬盘
            iuserInfoRepository = App.Current.Services.GetService<IUserInfoRepository>();
            userInfo = (UserInfo)App.Current.Services.GetService(typeof(UserInfo));
            users = iuserInfoRepository.Find(coputerinfo => coputerinfo.DiskID == macloaction);//获取本地登入记录
            IsActive = true;

        }

        //字段
        private IUserInfoRepository? iuserInfoRepository;
        private UserInfo? userInfo;
        private UserInfo? userInfoClone;
        private List<UserInfo>? users;

        //确定本机  获取登入下拉列表列表
        private string macloaction;
        ObservableCollection<UserInfoViewModel> userInfoList;
        public ObservableCollection<UserInfoViewModel> UserInfoList
        {
            get
            {
                if (userInfoList is null && users.Count > 0)
                {
                    userInfoList = new ObservableCollection<UserInfoViewModel>();
                    userInfoList.CollectionChanged += this.OnUserInfoListChanged;
                    CreateNewCustomer();
                    return userInfoList;
                }
                else
                {
                    return userInfoList;
                }

            }
        }
        private void OnUserInfoListChanged(object? sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null && e.NewItems.Count != 0)
                foreach (UserInfoViewModel uservm in e.NewItems)
                    uservm.DeletLocalCountHandler += this.OnUservmClose;

            if (e.OldItems != null && e.OldItems.Count != 0)
                foreach (UserInfoViewModel uservm in e.OldItems)
                    uservm.DeletLocalCountHandler -= this.OnUservmClose;
        }

        //方法

        /// <summary>
        /// 删除本地用户登入记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnUservmClose(object? sender, EventArgs e)
        {
            UserInfoViewModel uservm = sender as UserInfoViewModel;
            ///删除本地用户登入记录
            UserInfoList.Remove(uservm);
            users.Remove(uservm.UserInfoClone);
            uservm.Dispose();
        }
        void CreateNewCustomer()
        {
            foreach (var user in users)
            {
                var uservm = new UserInfoViewModel(user);
                UserInfoList.Add(uservm);
                this.SetActiveWorkspace(uservm);
            }

        }
        private void SetActiveWorkspace(UserInfoViewModel uservm)
        {

            var viewlist = (ListCollectionView)(CollectionViewSource.GetDefaultView(userInfoList));
            if (viewlist != null)
                viewlist.MoveCurrentTo(uservm);
        }

        [RelayCommand]
        private void NewRegister(object item)
        {

            RegisterView registerView =(RegisterView) App.Current.Services.GetService(typeof(RegisterView));
            registerView.Show();
        }

        [RelayCommand(CanExecute = nameof(CanLogin))]
        private void Login(object item)
        {
            bool isexistUser = iuserInfoRepository.Contains(UserName);
            if ( isexistUser == false)
            {
                //如果用户不存在
                ErrorMessage = "用户名或密码错误";
                return;
            }
            //用户存在,开始验证密码
            var user = iuserInfoRepository.Get( UserName);

            IntPtr inP1 = Marshal.SecureStringToBSTR(password);//inP为secureStr的句柄
            string ps1 = Marshal.PtrToStringBSTR(inP1);//ss="A"
            Marshal.ZeroFreeBSTR(inP1);//释放BSTR指针
            var cyptopass = CryptoHelper.HMACMD5Crypto(ps1, user.Salt);

            if (ps1 == "############" || cyptopass == user.Password   )
            {
                //登入成功
               

            }
            else
            {
                ErrorMessage = "用户名或密码错误";
                return;
            }


        }
        private bool CanLogin(object item)
        {

            return true;
        }


        //属性
        private string errorMessage;
        public string ErrorMessage
        {
            get => errorMessage;
            set
            {

                SetProperty(ref errorMessage, value);
            }

        }
        [ObservableProperty]
        private Visibility viewVisibility;

        private SecureString password = new();
        public SecureString Password
        {
            get
            {

                return password;
                //  CurrentUserInfoViewModel == null ? null : CurrentUserInfoViewModel.Password;
            }
            set
            {
                SetProperty(ref password, value);

            }
        }

        public string UserName
        {
            get => userInfo.Name;
            set
            {
                /*      //==================重点============================
                      if (value != "LYFWPFUI.MVVM.ViewModels.UserInfoViewModel")  就是因为这一句,才正常运行的
                      如果不加这一句代码,Combobox文本框,不管如何选择,都将显示LYFWPFUI.MVVM.ViewModels.UserInfoViewModel 文本。
                      
                       Combobox必须配置 SelectedValue="{Binding UserName}"(viewmodel)\SelectedValuePath="UserName"(model)
                */
                if (value != "LYFWPFUI.MVVM.ViewModels.UserInfoViewModel")
                {
                    SetProperty(userInfo.Name, value, userInfo, (item, m) => item.Name = m);
                }
            }
        }

        private ImageSource userImage;
        public ImageSource UserImage
        {
            get
            {
                if (userInfo.Photo == null) return null;
                //不能使用using 那样会把图片释放,导致图片不能显示出来。

                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.StreamSource = new MemoryStream(userInfo.Photo);
                image.EndInit();
                image.Freeze();//冻结减少内存消耗。
                return image;
            }

        }


        private UserInfoViewModel selectedItem;
        public UserInfoViewModel SelectedItem
        {
            get { return selectedItem; }
            set
            {
                SetProperty(ref selectedItem, value);

                if (value != null)
                {
                    //更新用户头像
                    userInfo.Photo = value.UserInfoClone.Photo;
                    OnPropertyChanged("UserImage");
                    //更新用户名
                    UserName = value.UserInfoClone.Name;


                    //更新记住密码
                    IsRememberPassword = value.UserInfoClone.IsRememberPassword;

                }
                else
                {

                    //删除已经选择的项,清空用户头像、 、记住密码

                    IsRememberPassword = false;
                    userInfo.Photo = null;
                    OnPropertyChanged("UserImage");//之所有这样写是因为 userInfo.Photo 

                    return;

                    return;

                }

            }
        }

        public bool IsRememberPassword
        {
            get => userInfo.IsRememberPassword;
            set
            {

                SetProperty(userInfo.IsRememberPassword, value, userInfo, (user, m) => user.IsRememberPassword = m);

            }
        }
     
        /// <summary>
        /// 根据选择下拉框中的项,显示  密码
        /// 因为要传入参数,所以不能写在SelectedItem属性中
        /// </summary>
        /// <param name="obj"></param>
        [RelayCommand]
        private void Updata(object[] obj)
        {
            SecureString secureStrings = new();
            /// 省略
        }

    }
}

 

效果

 

ComboBox控件重要Event

1、DropDownOpened

下拉框打开时发生。通常在用于获取下拉列表数据。

2、LostMouseCapture

当 ComboBox的IsEditable="true"时, 当这个元素失去鼠标选取时发生.LostMouseCapture事件表示 当这个元素失去鼠标选取时发生。当用户点击ComboboxItem后发生LostMouseCapture事件,该事件发生在MouseLeftButtonUp之后。

3、DropDownClosed

 该事件发生在LostMouseCapture事件之后。

posted @ 2022-11-20 16:03  小林野夫  阅读(5560)  评论(0编辑  收藏  举报
原文链接:https://www.cnblogs.com/cdaniu/