WPF 入门教程Border控件
Border 控件是一个装饰器控件,您可以使用它在另一个元素周围绘制边框、背景或什至两者。由于 WPF 面板不支持在其边缘周围绘制边框,因此边框控件可以帮助您实现这一点,只需通过边框控件包围例如面板即可。
使用上述边框的简单示例可能如下所示:
<Window x:Class="WpfTutorialSamples.Misc_controls.BorderSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BorderSample" Height="170" Width="200">
<Grid Margin="10">
<Border Background="GhostWhite" BorderBrush="Gainsboro" BorderThickness="1">
<StackPanel Margin="10">
<Button>Button 1</Button>
<Button Margin="0,10">Button 2</Button>
<Button>Button 3</Button>
</StackPanel>
</Border>
</Grid>
</Window>
在您定义背景或边框画笔和粗细之前,边框是完全无色的,所以这就是我在这里所做的,使用了 Background 、 BorderBrush 和 BorderThickness 属性。
带圆角的边框
我非常欣赏 Border 的一个特点是它很容易绕过拐角。看看这个稍微修改过的例子,其中的角现在是圆角的:
<Window x:Class="WpfTutorialSamples.Misc_controls.BorderSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BorderSample" Height="175" Width="200">
<Grid Margin="10">
<Border Background="GhostWhite" BorderBrush="Silver" BorderThickness="1" CornerRadius="8,8,3,3">
<StackPanel Margin="10">
<Button>Button 1</Button>
<Button Margin="0,10">Button 2</Button>
<Button>Button 3</Button>
</StackPanel>
</Border>
</Grid>
</Window>
我所做的就是添加 CornerRadius 属性。它可以使用单个值指定,该值将用于所有四个角,或者像我在此处的示例中所做的那样,我为右上角和左下角指定单独的值,然后是右下角和左下角。
边框颜色/厚度
上面的边框非常离散,但可以通过调节颜色和/或粗细轻松更改。由于 BorderThickness 属性属于 厚度 类型,您甚至可以单独操作每个边框宽度,或者通过为左右边框指定一个值,为顶部和底部边框指定一个值。
<Window x:Class="WpfTutorialSamples.Misc_controls.BorderSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BorderSample" Height="175" Width="200">
<Grid Margin="10">
<Border Background="GhostWhite" BorderBrush="DodgerBlue" BorderThickness="1,3,1,5">
<StackPanel Margin="10">
<Button>Button 1</Button>
<Button Margin="0,10">Button 2</Button>
<Button>Button 3</Button>
</StackPanel>
</Border>
</Grid>
</Window>
边框背景
Background 属性属于 Brush 类型,它开辟了许多很酷的可能性。正如在最初的例子中看到的,使用简单的颜色作为背景很容易,但实际上你也可以使用渐变,而且做起来并不难:
<Window x:Class="WpfTutorialSamples.Misc_controls.BorderSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BorderSample" Height="175" Width="200">
<Grid Margin="10">
<Border BorderBrush="Navy" BorderThickness="1,3,1,5">
<Border.Background>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="LightCyan" Offset="0.0" />
<GradientStop Color="LightBlue" Offset="0.5" />
<GradientStop Color="DarkTurquoise" Offset="1.0" />
</LinearGradientBrush>
</Border.Background>
<StackPanel Margin="10">
<Button>Button 1</Button>