Подтвердить что ты не робот

Установите CornerRadius на шаблон кнопки

Я хочу иметь Button, который определяет no CornerRadius и два других, которые делают, как я могу это достичь?

<Style TargetType="Button" x:Key="TabButton">
    <Setter Property="Background" Value="White" />
    <Setter Property="TextBlock.TextAlignment" Value="Center" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border CornerRadius="0" Background="White" BorderBrush="#ccc" BorderThickness="0,1,1,0" >
                    <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="Button" x:Key="TabButtonFirst" BasedOn="{StaticResource TabButton}">
    <Setter Property="CornerRadius" Value="3,0,0,0" />
</Style>

<Style TargetType="Button" x:Key="TabButtonLast" BasedOn="{StaticResource TabButton}">
    <Setter Property="CornerRadius" Value="0,0,0,3" />
</Style>
4b9b3361

Ответ 1

Поскольку Nitesh сказал, что у вас нет свойства CornerRadius на Button, это свойство границы, как вы показали в своем первом стиле, просто дублируйте свой первый стиль и измените CornerRadius, а затем назначьте его стилю соответствующей кнопки.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="Button" x:Key="TabButton">
            <Setter Property="Background" Value="White" />
            <Setter Property="TextBlock.TextAlignment" Value="Center" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border CornerRadius="0" Background="White" BorderBrush="#ccc" BorderThickness="0,1,1,0" >
                            <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="Button" x:Key="TabButtonFirst">
            <Setter Property="Background" Value="White" />
            <Setter Property="TextBlock.TextAlignment" Value="Center" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border CornerRadius="3,0,0,0" Background="White" BorderBrush="#ccc" BorderThickness="0,1,1,0" >
                            <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
         </Style>
         <Style TargetType="Button" x:Key="TabButtonLast">
            <Setter Property="Background" Value="White" />
            <Setter Property="TextBlock.TextAlignment" Value="Center" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border CornerRadius="0,0,0,3" Background="White" BorderBrush="#ccc" BorderThickness="0,1,1,0" >
                            <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
      </Window.Resources>
        <Grid Background="Black">
        <Button Style="{StaticResource TabButton}" Content="Button" Height="23" HorizontalAlignment="Left" Margin="12,72,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
        <Button Style="{StaticResource TabButtonFirst}" Content="Button" Height="23" HorizontalAlignment="Left" Margin="10,43,0,0" Name="button2" VerticalAlignment="Top" Width="75" />
        <Button Style="{StaticResource TabButtonLast}" Content="Button" Height="23" HorizontalAlignment="Left" Margin="12,101,0,0" Name="button3" VerticalAlignment="Top" Width="75" />
    </Grid>
</Window>

enter image description here

Ответ 2

Вы не ограничены свойствами зависимостей элемента управления, который вы шаблонируете. В этом случае, хотя у Button нет свойства CornerRadius, у Border оно есть, поэтому вместо него можно использовать Border.CornerRadius:

<Style TargetType="Button" x:Key="TabButton">
    <Setter Property="Background" Value="White" />
    <Setter Property="TextBlock.TextAlignment" Value="Center" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border CornerRadius="{TemplateBinding Border.CornerRadius}" 
                        Background="White" BorderBrush="#ccc" 
                        BorderThickness="0,1,1,0" >
                    <ContentPresenter x:Name="contentPresenter" 
                                      ContentTemplate="{TemplateBinding ContentTemplate}" 
                                      Content="{TemplateBinding Content}" 
                                      HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                      Margin="{TemplateBinding Padding}" 
                                      VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="Button" x:Key="TabButtonFirst" BasedOn="{StaticResource TabButton}">
    <Setter Property="Border.CornerRadius" Value="3,0,0,0" />
</Style>

<Style TargetType="Button" x:Key="TabButtonLast" BasedOn="{StaticResource TabButton}">
    <Setter Property="Border.CornerRadius" Value="0,0,0,3" />
</Style>

При таком подходе вам больше не нужно поддерживать несколько копий вашего шаблона управления.

Ответ 3

Просто создайте новую кнопку следующим образом:

<!--Button-->
            <Button  
               Name="myButton"
               Content="OK"
               FontFamily="Century Gothic"
               Foreground="white"
               Background="CornflowerBlue"
               BorderThickness="0"
               Padding="10"
               Margin="10,5">

                <Button.Resources>
                    <Style TargetType="{x:Type Border}">
                        <Setter Property="CornerRadius" Value="7"/>
                    </Style>
                </Button.Resources>

            </Button>

Ответ 4

Я бы сделал свой собственный пользовательский класс кнопок (унаследованный от Button), который включает свойство зависимостей CornerRadius. И тогда целевой тип вашего стиля станет новым классом, и вы можете использовать привязку шаблона для установки радиуса угла.

При таком подходе вам не нужно не только поддерживать несколько копий вашего шаблона управления, но вам не нужно создавать новый стиль для каждого раза, когда вы хотите изменить свой угловой радиус. Вы можете просто установить или привязать непосредственно к свойству зависимости CornerRadius.

Итак, ваш код для элемента управления может выглядеть примерно так:

public class MyCustomButton : Button
{
    public static readonly DependencyProperty CornerRadiusProperty =
        DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(MyCustomButton), new FrameworkPropertyMetadata(new CornerRadius(0)));

    public CornerRadius CornerRadius
    {
        get { return (CornerRadius)GetValue(CornerRadiusProperty); }
        set { SetValue(CornerRadiusProperty, value); }
    }
}

И XAML:

<Style TargetType="MyCustomButton" x:Key="TabButton">
    <Setter Property="Background" Value="White" />
    <Setter Property="TextBlock.TextAlignment" Value="Center" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="MyCustomButton">
                <Border CornerRadius="{TemplateBinding CornerRadius}" Background="White" BorderBrush="#ccc" BorderThickness="0,1,1,0" >
                    <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Итак, для ваших кнопок, которые не нуждаются в радиусе угла, поскольку свойство зависимостей по умолчанию равно 0, вам не нужно ничего делать. Для тех, у кого есть радиус угла, вы просто устанавливаете свойство зависимостей на соответствующее значение, как и свойство CornerRadius для нормальной границы.

Ответ 5

Вы можете использовать вложенные свойства для установки радиуса границы кнопки (также то же самое будет работать для текстовых полей).

Создать класс для прикрепленного свойства

public class CornerRadiusSetter
{
    public static CornerRadius GetCornerRadius(DependencyObject obj) => (CornerRadius)obj.GetValue(CornerRadiusProperty);

    public static void SetCornerRadius(DependencyObject obj, CornerRadius value) => obj.SetValue(CornerRadiusProperty, value);

    public static readonly DependencyProperty CornerRadiusProperty =
        DependencyProperty.RegisterAttached(nameof(Border.CornerRadius), typeof(CornerRadius),
            typeof(CornerRadiusSetter), new UIPropertyMetadata(new CornerRadius(), CornerRadiusChangedCallback));

    public static void CornerRadiusChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
    {
        Control control = sender as Control;

        if (control == null) return;

        control.Loaded += Control_Loaded;
    }

    private static void Control_Loaded(object sender, EventArgs e)
    {
        Control control = sender as Control;

        if (control == null || control.Template == null) return;

        control.ApplyTemplate();

        Border border = control.Template.FindName("border", control) as Border;

        if (border == null) return;

        border.CornerRadius = GetCornerRadius(control);
    }
}

Затем вы можете использовать синтаксис прикрепленного свойства для стилизации нескольких кнопок без дубликатов стилей:

<Button local:CornerRadiusSetter.CornerRadius="3,0,0,0">Click me!</Button>

<Button local:CornerRadiusSetter.CornerRadius="0,0,0,3">Click me!</Button>