WPF的页面设计和实用功能实现

news/2025/2/22 7:01:58

目录

一、TextBlock和TextBox

1. 在TextBlock中实时显示当前时间

二、ListView

1.ListView显示数据

三、ComboBox

1. ComboBox和CheckBox组合实现下拉框多选

四、Button

1. 设计Button按钮的边框为圆角,并对指针悬停时的颜色进行设置


一、TextBlock和TextBox

1. 在TextBlock中实时显示当前时间

可以通过绑定和定时器的方式来实现在TextBlock中显示当前实时时间。

<Window x:Class="RealTime.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:RealTime"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBlock Name="timeTextBlock"
                 HorizontalAlignment="Center"
                 VerticalAlignment="Center"
                 FontSize="24"
                 Width="300"
                 Height="40"/>
    </Grid>
</Window>

cs

using System.Text;
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;
using System.Timers;
using System.Windows.Threading;

namespace RealTime
{
    public partial class MainWindow : Window
    {
        private DispatcherTimer _timer;

        public MainWindow()
        {
            InitializeComponent();

            // 初始化定时器
            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromSeconds(1); // 每秒更新时间
            _timer.Tick += Timer_Tick; // 定时器的 Tick 事件
            _timer.Start(); // 启动定时器
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            // 获取当前时间并更新 TextBox
            timeTextBlock.Text = DateTime.Now.ToString("yyyy/MM/dd:HH:mm:ss");
        }
    }
}

 生成效果

说明1:

  • DispatcherTimer:WPF 提供了 DispatcherTimer 类,它允许你在指定的时间间隔后执行代码,并且能够在 UI 线程上安全地更新 UI 元素。DispatcherTimer 每次触发时会调用 Tick 事件。

  • Interval:设置为每秒触发一次。

  • Tick 事件:每秒钟触发一次,在 Timer_Tick 方法中更新时间。这里使用了 DateTime.Now.ToString("HH:mm:ss") 格式来显示当前的小时、分钟和秒。

说明2:

  • DateTime.Now.ToString("HH:mm:ss") 显示小时、分钟和秒。

  • DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") 显示完整的日期和时间。

二、ListView

1.ListView显示数据

<Window x:Class="ListView.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:ListView"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <ListView Name="StudentList"
                      MouseDoubleClick="StudentList_MouseDoubleClick"
                      Margin="10">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="姓名"
                                        Width="100"
                                        DisplayMemberBinding="{Binding Name}"></GridViewColumn>
                        <GridViewColumn Header="年龄"
                                        Width="100"
                                        DisplayMemberBinding="{Binding Age}"></GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
            <StackPanel Orientation="Horizontal">
                <Button Name="Mode1"
                        Margin="10"
                        HorizontalAlignment="Left"
                        Content="方式一"
                        Click="Mode1_Click"></Button>
                <Button Name="Mode2"
                        Margin="10"
                        HorizontalAlignment="Left"
                        Content="方式二"
                        Click="Mode2_Click"></Button>
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>

CS

using System.Collections.ObjectModel;
using System.Text;
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 ListView
{
    public class Student
    {
        public string? Name { get; set; }
        public string? Age { get; set; }
    }
    public partial class MainWindow : Window
    {
        public ObservableCollection<Student> Items { get; set; }
        public MainWindow()
        {
            InitializeComponent();           
        }

        private void Mode1_Click(object sender, RoutedEventArgs e)
        {
            StudentList.ItemsSource = null;
            StudentList.Items.Clear();
            // 初始化选项集合
            Items = new ObservableCollection<Student>
            {
                new Student { Name = "张三", Age = "20"},
                new Student { Name = "李四", Age = "21"},
                new Student { Name = "王五", Age = "22"},
                new Student { Name = "赵六", Age = "23"}
            };
            // 将Items集合绑定到ListView的ItemsSource
            StudentList.ItemsSource = Items;
        }

        private void Mode2_Click(object sender, RoutedEventArgs e)
        {
            StudentList.ItemsSource = null;
            StudentList.Items.Clear();
            StudentList.Items.Add(new Student { Name = "孙悟空", Age = "10000" });
            StudentList.Items.Add(new Student { Name = "悟能", Age = "5000" });
            StudentList.Items.Add(new Student { Name = "悟净", Age = "3000" });
            StudentList.Items.Add(new Student { Name = "唐僧", Age = "30" });
        }

        private void StudentList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if(StudentList.SelectedItem is Student student)
            {
                MessageBox.Show("姓名:" + student.Name + ",年龄:" + student.Age);
            }
        }
    }
}

页面显示说明:

初始页面

通过 ItemsSource = 列表的形式,将数据绑定到页面上,点击方式一

通过Items.Add(new 自定义类 { 属性 = "", 属性 = ""....... })的方式绑定数据,点击方式二

双击查看选择了那一条数据

三、ComboBox

1. ComboBox和CheckBox组合实现下拉框多选

说明:实现ComboBox下拉框是CheckBox,通过CheckBox的勾选情况判断选择了哪些项目

<Window x:Class="ComboBox.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:ComboBox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <!-- 定义多选ComboBox -->
            <ComboBox Name="multiSelectComboBox"
                      Width="200"
                      Height="30"
                      HorizontalAlignment="Left"
                      IsEditable="True"
                      StaysOpenOnEdit="True"
                      IsReadOnly="True"
                      Text="多选列表"
                      Margin="10">
                <!-- 定义ComboBox的ItemTemplate,包含一个CheckBox -->
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <CheckBox Content="{Binding Name}"
                                  IsChecked="{Binding IsSelected, Mode=TwoWay}" />
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
            <!-- 按钮显示所选项目 -->
            <Button Content="查看选择了什么选项"
                    Width="170"
                    Height="30"
                    VerticalAlignment="Top"
                    HorizontalAlignment="Left"
                    Margin="10"
                    Click="ShowSelectedOptions_Click" />
        </StackPanel>
    </Grid>
</Window>

CS

using System.Collections.ObjectModel;
using System.Text;
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 ComboBox
{
    public class Student
    {
        public string? Name { get; set; }        
        public bool IsSelected { get; set; }
    }
    public partial class MainWindow : Window
    {
        public ObservableCollection<Student> Items { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            // 初始化选项集合
            Items = new ObservableCollection<Student>
            {
                new Student { Name = "张三"},
                new Student { Name = "李四"},
                new Student { Name = "王五"},
                new Student { Name = "赵六"}
            };
            // 将Items集合绑定到ComboBox的ItemsSource
            multiSelectComboBox.ItemsSource = Items;
        }

        // 显示已选择的选项
        private void ShowSelectedOptions_Click(object sender, RoutedEventArgs e)
        {    
            // 获取所有IsSelected为true的项目
            var selectedItems = Items.Where(item => item.IsSelected).Select(item => item.Name).ToList();
            // 显示选择的项目
            multiSelectComboBox.Text = "你选择了: " + string.Join(", ", selectedItems);
        }
    }
}

页面

点击下拉框,选择两个项目

点击按钮

四、Button

1. 设计Button按钮的边框为圆角,并对指针悬停时的颜色进行设置

<Window x:Class="Button_Coner.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:Button_Coner"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <!-- 定义带有悬停效果的按钮样式 -->
        <Style TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border x:Name="border" 
                                Background="{TemplateBinding Background}" 
                                BorderBrush="{TemplateBinding BorderBrush}" 
                                BorderThickness="{TemplateBinding BorderThickness}"
                                CornerRadius="20">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <!-- 悬停时改变背景颜色 -->
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="border" Property="Background" Value="LightCoral"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

    <Grid>
        <Button Width="150" Height="50" Content="圆角按钮" Background="LightBlue"/>
        <Button Width="100" Height="50" Content="测试" BorderBrush="Green" BorderThickness="2" HorizontalAlignment="Left"></Button>
    </Grid>
</Window>

样式


http://www.niftyadmin.cn/n/5861849.html

相关文章

ElasticSearch公共方法封装

业务场景 1、RestClientBuilder初始化&#xff08;同时支持单机与集群&#xff09; 2、发送ES查询请求公共方法封装&#xff08;支持sql、kql、代理访问、集群访问、鉴权支持&#xff09; 3、判断ES索引是否存在&#xff08;/_cat/indices/${indexName}&#xff09; 4、判断ES…

AI基础:数据可视化简易入门(Matplotlib和Seaborn)

Matplotlib是一个Python的2D绘图库&#xff0c;它以各种硬拷贝和跨平台的交互式环境生成出版质量级别的图形。 Seaborn是基于Python且非常受欢迎的图形可视化库&#xff0c;在Matplotlib的基础上进行了更高级别的封装&#xff0c;使作图更加方便快捷。 1 Matplotlib 1.1 通过…

微信问题总结(onpageshow ,popstate事件)

此坑描述 订单详情某按钮点击&#xff0c;通过window.location.href跳转到&#xff08;外部&#xff09;第三方链接后&#xff0c;回退后&#xff0c;在ios中生命周期和路由导航钩子都失效了&#xff0c;无法触发。 在安卓中无视此坑&#xff0c; 回退没有问题 解决 原因&am…

MySQL MHA 部署全攻略:从零搭建高可用数据库架构

文章目录 1.MHA介绍2.MHA组件介绍3.集群规划4.服务器初始化5.MySQL集群部署5.1 安装MySQL集群5.2 配置一主两从5.3 测试MySQL主从5.4 赋予MHA用户连接权限 6.安装MHA环境6.1 安装MHA Node6.2 安装MHA Manager 7.配置MHA环境8.MySQL MHA高可用集群测试8.1 通过VIP连接MySQL8.2模…

精准测量PMD:OCI-V光矢量分析系统赋能光纤通信性能优化

在光纤通信技术飞速发展的今天&#xff0c;偏振模色散&#xff08;PMD&#xff09;已成为制约系统性能的核心瓶颈之一。PMD会导致信号失真、码间串扰&#xff0c;并限制传输距离&#xff0c;严重影响系统的带宽容量和传输可靠性。因此&#xff0c;精准测量PMD对于优化光纤通信系…

kafka-集群缩容

一. 简述&#xff1a; 当业务增加时&#xff0c;服务瓶颈&#xff0c;我们需要进行扩容。当业务量下降时&#xff0c;为成本考虑。自然也会涉及到缩容。假设集群有 15 台机器&#xff0c;预计缩到 10 台机器&#xff0c;那么需要做 5 次缩容操作&#xff0c;每次将一个节点下线…

Ubuntu 22.04 Install deepseek

前言 deepseekAI助手。它具有聊天机器人功能&#xff0c;可以与用户进行自然语言交互&#xff0c;回答问题、提供建议和帮助解决问题。DeepSeek 的特点包括&#xff1a; 强大的语言理解能力&#xff1a;能够理解和生成自然语言&#xff0c;与用户进行流畅的对话。多领域知识&…

使用Open WebUI下载的模型文件(Model)默认存放在哪里?

&#x1f3e1;作者主页&#xff1a;点击&#xff01; &#x1f916;Ollama部署LLM专栏&#xff1a;点击&#xff01; ⏰️创作时间&#xff1a;2025年2月21日21点21分 &#x1f004;️文章质量&#xff1a;95分 文章目录 使用CMD安装存放位置 默认存放路径 Open WebUI下…