wp7 给TextBox设置圆角边框

这只是一个很简单小技巧,大牛们就不要再来喷小弟。。

我就喜欢将一件很简单事情做到很完美。。。

首先准备好一张背景图

在最外层grid 加上这段代码:代码意思给页面加上背景图

 <Grid.Background>
            <ImageBrush ImageSource="/Images/bg.png"></ImageBrush>
  </Grid.Background>

下面是关键部分

主要用到一个Border 跟TextBox控件

Border作用就是加个边框效果

 <Border BorderThickness="1" BorderBrush="Gray" Height="72" Width="300" CornerRadius="10">
                <TextBox Text="请输入密码"></TextBox>
</Border>

还有很多细节问题处理,如下面红色地方 跟背景不匹配(控件默认是白色)

接下来我用取色器取出周边颜色 ,给文本框加上一个属性Background="#f6fbff"

<Border BorderThickness="1" BorderBrush="Gray" Height="72" Width="300" CornerRadius="10">
                <TextBox Text="请输入密码" Background="#f6fbff"></TextBox>
</Border>

细心点就发现TextBox还多出边框是白色,下面我给文本设置上周围背景色

 <Border BorderThickness="1" BorderBrush="Gray" Height="72" Width="300" CornerRadius="10">
                <TextBox Text="请输入密码" Background="#f6fbff" BorderBrush="#f6fbff"></TextBox>
</Border>

似乎很完美解决了...

但是这不是我想要的,假如我页面有一百个这样文本框,复制一百次这样子代码??

用户控件可以减少我部分代码量

用户控件代码:

  public partial class MyTextBox : UserControl
    {
        //文本框值
        private string _Text = "";
        public string MyText
        {
            get { return _Text; }
            set { _Text = value; }
        }
        //高度
        private double _Height = 72;
        public double MyHeight
        {
            get { return _Height; }
            set { _Height = value; }
        }

        //宽度
        private double _Width = 300;
        public double MyWidth
        {
            get { return _Width; }
            set { _Width = value; }
        }
        private string _Background = "#f6fbff";
        public string MyBackground
        {
            get { return _Background; }
            set { _Background = value; }
        }
        public MyTextBox()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MyTextBox_Loaded);
        }

        void MyTextBox_Loaded(object sender, RoutedEventArgs e)
        {
            txtBox.Text = MyText;
            border.Height = MyHeight;
            border.Width = MyWidth;
            string bg = this.MyBackground.Replace("#", "");

            byte r = Convert.ToByte(bg.Substring(0, 2));
            byte g = Convert.ToByte(bg.Substring(2, 2));
            byte b = Convert.ToByte(bg.Substring(4, 2));
            var color = new SolidColorBrush(Color.FromArgb(255, r, g, b));
            txtBox.Background = color;
            txtBox.BorderBrush = color;
        }

    }

这里我只写三个属性,做了一些简单处理。。。。

之后在页面拖这个控件,设置几个属性就可以使用,详细请查看源代码

  <my:MyTextBox HorizontalAlignment="Left" MyBackground="#222222" Margin="34,173,0,0" x:Name="myTextBox1" VerticalAlignment="Top"  Tap="myTextBox1_Tap" MyHeight="70" MyWidth="400" MyText="12221" />

其实里面很多东西都没有考虑进去,等我完成这个wp7小作品,我会逐步完善这个控件

同样项目源代码我也会共享出来。。。

TextBlockCornerRadius.rar

原文地址:https://www.cnblogs.com/walleyekneel/p/2858457.html