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

如何在WPF窗体中用纯XAML添加三角形背景并放置登录面板

WPF纯XAML实现绿色三角形背景+登录面板布局

直接利用Grid的层叠布局特性即可实现,先绘制背景三角形,再在上方放置登录面板,以下是完整实现代码:

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="登录" Height="450" Width="800">
    <Grid>
        <!-- 绿色三角形背景 -->
        <Polygon Fill="#2ECC71" Stretch="Fill">
            <Polygon.Points>
                <!-- 当前为右上直角三角形,可根据需求修改三个顶点坐标 -->
                <Point X="0" Y="0"/>
                <Point X="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=ActualWidth}" Y="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=ActualHeight}"/>
                <Point X="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=ActualWidth}" Y="0"/>
            </Polygon.Points>
        </Polygon>

        <!-- 登录面板,自动遮挡部分三角形 -->
        <Border Background="White" CornerRadius="8" Margin="50" Width="300" Height="300" 
                HorizontalAlignment="Left" VerticalAlignment="Center">
            <StackPanel VerticalAlignment="Center" Margin="20">
                <TextBlock Text="用户名" Margin="0 0 0 5"/>
                <TextBox Width="250" Height="35" Margin="0 0 0 15"/>
                <TextBlock Text="密码" Margin="0 0 0 5"/>
                <PasswordBox Width="250" Height="35" Margin="0 0 0 15"/>
                <Button Content="登录" Width="250" Height="35" Background="#2ECC71" Foreground="White"/>
            </StackPanel>
        </Border>
    </Grid>
</Window>

关键说明:

  • 层叠逻辑:Grid容器中后声明的元素会自动覆盖在先声明的元素上方,因此登录面板会自然遮挡部分三角形。
  • 自适应调整:通过绑定Window.ActualWidth和ActualHeight,三角形会随窗体大小变化自动适配,无需固定尺寸。
  • 形状自定义:修改Polygon.Points中的三个坐标即可改变三角形的位置和形态。例如要实现左下直角三角形,可将Points改为:
    <Point X="0" Y="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=ActualHeight}"/>
    <Point X="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=ActualWidth}" Y="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=ActualHeight}"/>
    <Point X="0" Y="0"/>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:15:34