You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF自定义最小化/关闭按钮:如何添加全局点击事件实现窗口操作

可复用WPF自定义窗口控制按钮实现方案

需求说明

需要创建带自定义样式的WPF最小化、关闭按钮,可在多窗口复用,无需在每个窗口编写this.WindowState = WindowState.Minimized;或关闭窗口的代码,点击按钮自动触发对应功能。

解决方案步骤

1. 创建自定义最小化按钮控件

在项目中新建自定义控件类MinimizeButton,继承自Button,在构造函数中绑定点击事件,自动查找父窗口并执行最小化逻辑:

using System.Windows;
using System.Windows.Controls;

namespace WpfApp2
{
    public class MinimizeButton : Button
    {
        public MinimizeButton()
        {
            Click += MinimizeButton_Click;
        }

        private void MinimizeButton_Click(object sender, RoutedEventArgs e)
        {
            Window parentWindow = Window.GetWindow(this);
            parentWindow?.WindowState = WindowState.Minimized;
        }
    }
}

2. 创建自定义关闭按钮控件

同理,创建CloseButton类,实现关闭窗口的逻辑:

using System.Windows;
using System.Windows.Controls;

namespace WpfApp2
{
    public class CloseButton : Button
    {
        public CloseButton()
        {
            Click += CloseButton_Click;
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Window parentWindow = Window.GetWindow(this);
            parentWindow?.Close();
        }
    }
}

3. 在资源字典中定义控件样式

修改你的ResourceDictionary,分别为两个自定义按钮设置样式:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp2">

    <!-- 最小化按钮样式 -->
    <Style TargetType="{x:Type local:MinimizeButton}" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="Background" Value="Yellow"/>
        <Setter Property="Width" Value="100"/>
        <Setter Property="Height" Value="100"/>
        <Setter Property="Content" Value="最小化"/>
    </Style>

    <!-- 关闭按钮样式 -->
    <Style TargetType="{x:Type local:CloseButton}" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="Background" Value="Red"/>
        <Setter Property="Width" Value="100"/>
        <Setter Property="Height" Value="100"/>
        <Setter Property="Content" Value="关闭"/>
    </Style>

</ResourceDictionary>

4. 在主窗口中使用自定义按钮

在主窗口XAML中引用自定义控件命名空间,直接使用按钮即可,无需额外编写事件代码:

<Window x:Class="WpfApp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp2"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <local:MinimizeButton/>
        <local:CloseButton/>
    </StackPanel>
</Window>

关键说明

  • 通过Window.GetWindow(this)自动获取按钮所在的顶级窗口,无需手动绑定窗口实例
  • 自定义控件的逻辑封装在后台代码中,所有使用该控件的窗口都会自动继承功能
  • 样式可按需修改,保持控件功能与样式分离

内容的提问来源于stack exchange,提问作者Shehab Fekry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:17:34