正常情况下WPF自带的Border都能满足我们日常使用。但某些情况下遇到比较复杂的需求时候原生的效果还是不能满足我们的需求。例如以下这种立体边框:
当然如果这种尺寸是固定的,我们只需要美工提供图片就可以了,但如果尺寸是可以动态变动的我们就不能使用图片作为背景了,因为背景边框也是会拉伸的,谁叫咋们的WPF不能像IOS开发那样设置一个值边框就不会拉伸·······
好吧,我们只有自己动手实现一个四个边框不同颜色的border来实现了。
1.首先,我们创建一个类,继承自Borde。再新建4个边框的Brush依赖属性保存用户设置的四个Brush。
public Brush LeftBorderBrush { get { return (Brush)GetValue(LeftBorderBrushProperty); } set { SetValue(LeftBorderBrushProperty, value); } } public static readonly DependencyProperty LeftBorderBrushProperty = DependencyProperty.Register("LeftBorderBrush", typeof(Brush), typeof(FouerColorBorder), new PropertyMetadata(null)); public Brush TopBorderBrush { get { return (Brush)GetValue(TopBorderBrushProperty); } set { SetValue(TopBorderBrushProperty, value); } } public static readonly DependencyProperty TopBorderBrushProperty = DependencyProperty.Register("TopBorderBrush", typeof(Brush), typeof(FouerColorBorder), new PropertyMetadata(null)); public Brush RightBorderBrush { get { return (Brush)GetValue(RightBorderBrushProperty); } set { SetValue(RightBorderBrushProperty, value); } } public static readonly DependencyProperty RightBorderBrushProperty = DependencyProperty.Register("RightBorderBrush", typeof(Brush), typeof(FouerColorBorder), new PropertyMetadata(null)); public Brush BottomBorderBrush { get { return (Brush)GetValue(BottomBorderBrushProperty); } set { SetValue(BottomBorderBrushProperty, value); } } public static readonly DependencyProperty BottomBorderBrushProperty = DependencyProperty.Register("BottomBorderBrush", typeof(Brush), typeof(FouerColorBorder), new PropertyMetadata(null));
2.接着我们得重写OnRender方法。
protected override void OnRender(System.Windows.Media.DrawingContext dc) {