如何在WPF中为自定义文本框控件指定角半径

本文关键字:控件 文本 WPF 自定义 | 更新日期: 2023-09-27 18:16:47

我用下面的代码创建了自定义文本框。但是我不能为它提供圆角边框。

public class FilteredTextBox : TextBox
{

    public FilteredTextBox()
        : base()
    {
        IsNumeric = false;
        IsRegex = false;
        IsRequired = false;
        ErrorMsg = "";
        RegexText = "";
        HorizontalAlignment = HorizontalAlignment.Stretch;
        Margin = new Thickness(0);
        BorderThickness = new Thickness(1);
        var border = new Border {CornerRadius = new CornerRadius(4)};
     }
   }

请指点我一下。

如何在WPF中为自定义文本框控件指定角半径

您可以为您的自定义TextBox设置样式:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid>
    <Grid.Resources>
      <Style x:Key="CustomTextBoxStyle" TargetType="{x:Type TextBox}">
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBoxBase}">
              <Border
                CornerRadius="4"
                Padding="2"
                Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="1" >
                <ScrollViewer Margin="0" x:Name="PART_ContentHost"/>
              </Border>
            </ControlTemplate>
          </Setter.Value>
        </Setter>
      </Style>
    </Grid.Resources>
    <Grid VerticalAlignment="Center" HorizontalAlignment="Center">
      <CustomTextBox Style="{StaticResource CustomTextBoxStyle}" Text="TextBox with CornerRadius" BorderBrush="Black" />
    </Grid>
  </Grid>
</Page>

希望能有所帮助

我想把这个作为对punker76的伟大回应的补充:

如果你想修改当前。net中可用的FrameworkElement对象的默认样式,有很多方法可以实现它,但我总是喜欢这个方便的工具:

Show Me The Template