ComboBox绑定、DatePicker、智能提示、清除按钮、模糊查询、文字动画、文字图标、GIF、颜色动画等

31-ComboBox绑定数据源MVVM模式

界面XAML代码

<Window x:Class="ComboxDemo.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:local="clr-namespace:ComboxDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
        <ComboBox 
                        Height="25" 
                        Width="200" 
                        VerticalContentAlignment="Center"
                        ItemsSource="{Binding GongYiList}"
                        SelectedItem="{Binding SelectedGongYi}"
                        DisplayMemberPath="Name"
                        SelectedValuePath="Value"/>
    </StackPanel>
</Window>Code language: HTML, XML (xml)

创建一个实体类

namespace ComboxDemo
{
    public class ComboxItemModel
    {
        public string Name
        {
            get;
            set;
        }

        public string Value
        {
            get;
            set;
        }
    }
}Code language: JavaScript (javascript)

我们的viewmodel

namespace ComboxDemo
{
    public class MyViewModel:INotifyPropertyChanged
    {
        public MyViewModel()
        {
            //此处可以查询数据库初始化数据源
            this.GongYiList = new List<ComboxItemModel>()
            {
                new ComboxItemModel { Name = "A", Value = "01" },
                new ComboxItemModel { Name = "B", Value = "02" }
            };

            //this.SelectedGongYi = new ComboxItemModel();
            this.SelectedGongYi = this.GongYiList[0];
        }

        private List<ComboxItemModel> gongYiList;

        private ComboxItemModel selectedGongYi;

        public List<ComboxItemModel> GongYiList
        {
            get { return gongYiList; }
            set
            {
                gongYiList = value;
                NotifyPropertyChanged("GongYiList");
            }
        }

        private void NotifyPropertyChanged(string column)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(column));
        }

        public ComboxItemModel SelectedGongYi
        {
            get { return selectedGongYi; }
            set
            {
                selectedGongYi = value;
                NotifyPropertyChanged("SelectedGongYi");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}Code language: HTML, XML (xml)

设置数据源

public partial class MainWindow : Window
    {
        MyViewModel vm = new MyViewModel();
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = vm;
        }
    }

设置默认选择项

public MyViewModel()
        {
            //此处可以查询数据库初始化数据源
            this.GongYiList = new List<ComboxItemModel>()
            {
                new ComboxItemModel { Name = "A", Value = "01" },
                new ComboxItemModel { Name = "B", Value = "02" }
            };

            //this.SelectedGongYi = new ComboxItemModel();
            this.SelectedGongYi = this.GongYiList[0];
        }Code language: JavaScript (javascript)

32-DatePicker日期控件绑定MVVM模式

日期范围的绑定,而且我们还希望做到 控制日期范围的联动 并且限制一个月

<Window x:Class="DataPickerDemo.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:local="clr-namespace:DataPickerDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <StackPanel Orientation="Horizontal">
        <DatePicker HorizontalAlignment="Left" VerticalAlignment="Center" Height="25" Width="140" VerticalContentAlignment="Center" Text="{Binding StartTime,Mode=TwoWay}"></DatePicker>
        <Label VerticalContentAlignment="Center">-</Label>
        <DatePicker HorizontalAlignment="Left" VerticalAlignment="Center" Height="25" Width="140" VerticalContentAlignment="Center"  Text="{Binding EndTime,Mode=TwoWay}"></DatePicker>
        </StackPanel>
    </StackPanel>
</Window>Code language: HTML, XML (xml)
namespace DataPickerDemo
{
    public class MyViewModel:INotifyPropertyChanged
    {

        public MyViewModel()
        {
            
        }

        private DateTime startTime;
        private DateTime endTime;

        public event PropertyChangedEventHandler PropertyChanged;

        public DateTime StartTime
        {
            get { return startTime; }
            set
            {
                startTime = value;
                this.endTime = startTime.AddDays(31);
                NotifyPropertyChanged("EndTime");
                NotifyPropertyChanged("StartTime");
            }
        }

        private void NotifyPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public DateTime EndTime
        {
            get { return endTime; }
            set
            {
                endTime = value;
                this.startTime = endTime.AddDays(-31);
                NotifyPropertyChanged("EndTime");
                NotifyPropertyChanged("StartTime");
            }
        }
    }
}Code language: PHP (php)
/// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        MyViewModel vm = new MyViewModel();

        public MainWindow()
        {
            InitializeComponent();

            vm.EndTime = DateTime.Now;
            this.DataContext = vm;
        }
    }Code language: HTML, XML (xml)

33-使用Combox实现智能提示

本文参考 http://chaochaoblog.com/archives/3197

<ComboBox 
                        Name="danHaoCombox"
                        HorizontalAlignment="Left"
                        Grid.Row="1" 
                        Grid.Column="2" 
                        VerticalAlignment="Center" 
                        Height="25" 
                        Width="200" 
                        VerticalContentAlignment="Center"
                        ItemsSource="{Binding DanHaoList}"
                        SelectedItem="{Binding SelectedDanHao}"
                        DisplayMemberPath="Name"
                        SelectedValuePath="Value"  
                        IsEditable="True"
                        />Code language: HTML, XML (xml)

ViewModel中

namespace DropDownDemo
{
    public class MyViewModel : INotifyPropertyChanged
    {
        public MyViewModel()
        {
            DanHaoList = new List<ComboxItemModel>();
            SelectedDanHao = new ComboxItemModel();
        }
        private List<ComboxItemModel> danHaoList;

        private ComboxItemModel selectedDanHao;

        public List<ComboxItemModel> DanHaoList
        {
            get { return danHaoList; }
            set
            {
                danHaoList = value;
                NotifyPropertyChanged("DanHaoList");
            }
        }

        private void NotifyPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public ComboxItemModel SelectedDanHao
        {
            get { return selectedDanHao; }
            set
            {
                selectedDanHao = value;
                NotifyPropertyChanged("SelectedDanHao");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}Code language: PHP (php)

xaml.cs中的事件绑定

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DropDownDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        MyViewModel vm;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void ComboBoxEditTextChange(MainWindow mSIndexPage, object p)
        {
            vm.DanHaoList.Clear();
            for (int i = 0; i < 10; i++)
            {
                vm.DanHaoList.Add(new ComboxItemModel() { Name = this.danHaoCombox.Text + i, Value = this.danHaoCombox.Name + i });
            }
            vm.DanHaoList = new List<ComboxItemModel>(vm.DanHaoList);
            this.danHaoCombox.IsDropDownOpen = true;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            vm = new MyViewModel();

            this.DataContext = vm;

            ControlTemplate cbbTemplate = danHaoCombox.Template;
            TextBox editBox = (TextBox)cbbTemplate.FindName("PART_EditableTextBox", danHaoCombox);
            editBox.TextChanged += delegate
            {
                this.ComboBoxEditTextChange(this, null);
            };
        }
    }
}

34-简单实现清除按钮

private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.danHaoCombox.Text = string.Empty;            
        }Code language: JavaScript (javascript)
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <Grid Width="200">
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
        <ComboBox Grid.Row="0" Grid.Column="0"
                        Name="danHaoCombox"
                        Height="25" 
                        Width="200" 
                        VerticalContentAlignment="Center"
                        ItemsSource="{Binding DanHaoList}"
                        SelectedItem="{Binding SelectedDanHao}"
                        DisplayMemberPath="Name"
                        SelectedValuePath="Value"  
                        IsEditable="True"
                        />
            <Button Margin="130,0,0,0" Grid.Row="0" Grid.Column="0" Width="20" Height="25" Background="Transparent" Click="Button_Click" BorderThickness="0" Content="X"></Button>
        </Grid>
    </StackPanel>Code language: HTML, XML (xml)

35-WPF ComboBox 模糊查询和下拉自动展开时的光标控制

WPF ComboBox 模糊查询+下拉自动展开时的光标控制

WPF ComboBox 模糊查询+下拉自动展开时设置:

xml设置ComboBox属性 IsEditable=”True”,IsTextSearchEnabled=”False”

<ComboBox Grid.Row="0" Grid.Column="0"
                        Name="danHaoCombox"
                        Height="25" 
                        Width="200" 
                        VerticalContentAlignment="Center"
                        ItemsSource="{Binding DanHaoList}"
                        SelectedItem="{Binding SelectedDanHao}"
                        DisplayMemberPath="Name"
                        SelectedValuePath="Value"  
                        IsEditable="True"
                  KeyUp="danHaoCombox_KeyUp"
                  IsTextSearchEnabled="False"
                        />Code language: HTML, XML (xml)

模糊查询使用键盘事件如 KeyUp查询结果刷新下列选项

private void danHaoCombox_KeyUp(object sender, KeyEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            this.vm.UpdateComboBoxItems(comboBox.Text);  //刷新下拉选项
            if (this.vm.DanHaoList.Count > 0)
            { 
                comboBox.IsDropDownOpen = true;
            }
            TextBox textBox = (TextBox)comboBox.Template.FindName("PART_EditableTextBox", comboBox);
            //每次填写后  光标定位在文本的后面
            textBox.SelectionStart = textBox.Text.Length;
        }Code language: JavaScript (javascript)

这个方法在vm实体类里面 目的就是更新数据源

internal void UpdateComboBoxItems(string text)
        {
            DanHaoList.Clear();
            if (string.IsNullOrEmpty(text))
            {
                return;
            }
            for (int i = 0; i < 10; i++)
            {
                DanHaoList.Add(new ComboxItemModel() { Name = text + i, Value = text + i });
            }
            DanHaoList = new List<ComboxItemModel>(DanHaoList);
        }Code language: JavaScript (javascript)

36-WPF文字动画跳动和闪烁

<Window x:Class="AnimationDemo.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:local="clr-namespace:AnimationDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel x:Name="gdLogo" Grid.Row="0" >
            <TextBlock Name="RealText" FontFamily="Segoe UI" FontSize="30" Margin="10,30" Foreground="Black">
                        北盟网校
                <TextBlock.TextEffects>
                    <!-- The TextEffect to animate. -->
                    <TextEffect PositionCount="3" x:Name="MyTextEffect">
                        <TextEffect.Transform>
                            <TranslateTransform x:Name="TextEffectTranslateTransform"/>
                        </TextEffect.Transform>
                        <TextEffect.Foreground>
                            <SolidColorBrush x:Name="TextEffectTranslateTransform2"/>
                        </TextEffect.Foreground>
                    </TextEffect>
                </TextBlock.TextEffects>
                <TextBlock.Triggers>
                    <EventTrigger RoutedEvent="TextBlock.Loaded">
                        <BeginStoryboard>
                            <Storyboard>
                                <!-- Animates the Y factor of the 
                                        TextEffect's TranslateTransform. -->
                                <DoubleAnimation
                                    Storyboard.TargetName="TextEffectTranslateTransform"
                                    Storyboard.TargetProperty="Y"                  
                                    From="-3"
                                    To="3"
                                    Duration="00:00:0.25"
                                    RepeatBehavior="Forever"
                                    AutoReverse="True" />
                                <ColorAnimation  Storyboard.TargetName="TextEffectTranslateTransform2"
                                                 Storyboard.TargetProperty="Color"    
            Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever" From="Red" To="White">
                                </ColorAnimation>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </TextBlock.Triggers>
            </TextBlock>
        </StackPanel>

    </Grid>
</Window>Code language: HTML, XML (xml)

控制文字的位置 和颜色变化

37-文字跳动效果样式Style-控制多个文本动画

我们上一节课动画是直接写在TextBlock内部的。所以不能重复利用

<Window x:Class="WpfApplication3.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:local="clr-namespace:WpfApplication3"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="TextBlock">
            <Style.Triggers>
                <EventTrigger RoutedEvent="Loaded">
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard Storyboard.TargetProperty="FontSize">
                                <DoubleAnimation  From="0" To="20" Duration="0:0:1" RepeatBehavior="Forever" AutoReverse="True" >
                                </DoubleAnimation>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger.Actions>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel x:Name="gdLogo" Grid.Row="0" >
            <TextBlock FontFamily="Segoe UI" Margin="10,30" Foreground="Black">
                        北盟网校1
            </TextBlock>
            <TextBlock FontFamily="Segoe UI" Margin="10,30" Foreground="Black">
                        北盟网校2
            </TextBlock>
            <TextBlock Name="RealText" Margin="10,30" Foreground="Black">
                        北盟网校3
            </TextBlock>
        </StackPanel>
    </Grid>
</Window>Code language: HTML, XML (xml)

38-文字图标和动画跳动

我们可以使用一些文字图标。比如在wpf里面使用awesome字体 然后增加样式 使得图标动态变化。

首先是文字图标在WPF中的应用

下载文字图标 https://fontawesome.dashgame.com/

<Window x:Class="WpfApplication3.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:local="clr-namespace:WpfApplication3"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style x:Key="FontAwesome" TargetType="TextBlock">
            <Setter Property="FontFamily" Value="pack://application:,,,/#FontAwesome" />
            <Setter Property="Width" Value="30"></Setter>
            <Setter Property="Height" Value="30"></Setter>
            <Setter Property="TextAlignment" Value="Center"></Setter>
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
            <Setter Property="FontSize" Value="30"></Setter>
            <Setter Property="Foreground" Value="Green"></Setter>
            <Setter Property="Margin" Value="3,7,3,0"></Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel x:Name="gdLogo" Grid.Row="0" >
            <TextBlock Text="&#xf2d5;" Style="{StaticResource FontAwesome}" />
            <TextBlock Text="&#xf01a;" Style="{DynamicResource FontAwesome}" />
        </StackPanel>
    </Grid>
</Window>Code language: HTML, XML (xml)

如果我们希望它动的话 就增加动画效果

<Window x:Class="WpfApplication3.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:local="clr-namespace:WpfApplication3"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style x:Key="FontAwesome" TargetType="TextBlock">
            <Setter Property="FontFamily" Value="pack://application:,,,/#FontAwesome" />
            <Setter Property="Width" Value="60"></Setter>
            <Setter Property="Height" Value="60"></Setter>
            <Setter Property="TextAlignment" Value="Center"></Setter>
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
            <Setter Property="FontSize" Value="60"></Setter>
            <Setter Property="Foreground" Value="Green"></Setter>
            <Setter Property="Margin" Value="3,7,3,0"></Setter>
            <Style.Triggers>
                <EventTrigger RoutedEvent="Loaded">
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard Storyboard.TargetProperty="FontSize">
                                <DoubleAnimation To="60" Duration="0:0:1" From="0" RepeatBehavior="Forever"
                                    AutoReverse="True" >
                                </DoubleAnimation>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger.Actions>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel x:Name="gdLogo" Grid.Row="0" >
            <TextBlock Text="&#xf2d5;" Style="{StaticResource FontAwesome}" />
            <TextBlock Text="&#xf01a;" Style="{DynamicResource FontAwesome}" />
        </StackPanel>
    </Grid>
</Window>Code language: HTML, XML (xml)

39-WPF显示GIF动画

WPF的Image控件不能很好的支持.gif文件。解决办法有如下2种。

以前如果在winform里面 显示gif 很简单 只需要增加picbox就可以了 但是在WPF里面 就没有这样。比如下面 它是不会动的

<Grid>
        <Image Source="load.gif" />
    </Grid>Code language: HTML, XML (xml)

使用MediaElement

<Grid>
        <MediaElement Source="file://E:\更多--北盟网校\WPF进阶\Gif\Gif\load.gif" />
    </Grid>Code language: HTML, XML (xml)

使用时,注意要使用 “file://”和gif文件的绝对路径。

40-WPF颜色动画中动态渐变

具体大家可以参考这一集 36-WPF文字动画跳动和闪烁

<Style x:Key="FontAwesome2" TargetType="TextBlock">
            <Setter Property="FontFamily" Value="pack://application:,,,/#FontAwesome" />
            <Setter Property="Width" Value="20"></Setter>
            <Setter Property="Height" Value="20"></Setter>
            <Setter Property="TextAlignment" Value="Center"></Setter>
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
            <Setter Property="FontSize" Value="12"></Setter>
            <Setter Property="Foreground" Value="Green"></Setter>
            <Setter Property="Margin" Value="3,14,3,0"></Setter>
            <Style.Triggers>
                <EventTrigger RoutedEvent="Loaded">
                    <EventTrigger.Actions>
                        <BeginStoryboard>
                            <Storyboard Storyboard.TargetProperty="Foreground.Color">
                               <ColorAnimation    
            Duration="0:0:10" AutoReverse="True" RepeatBehavior="Forever" From="Red" To="White">
                                </ColorAnimation>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger.Actions>
                </EventTrigger>
            </Style.Triggers>
        </Style>Code language: HTML, XML (xml)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注