Search code examples
wpfuser-controlsshapes

WPF User Control - Round corners programmatically


Another WPF question...

<UserControl x:Class="TKEApp.Components.UserControls.ButtonControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid Background="Black">
        <TextBlock Foreground="White" Background="Brown" Name="lblCaption" TextAlignment="Center"></TextBlock>
    </Grid>
</UserControl>

Somwhere in the application code I have an instance of this control and I need to make it's corners rounded programmatically. Is this possible?


Solution

  • You need to use a Border to provide rounded corners, so you could do something like this:

    <UserControl x:Class="TKEApp.Components.UserControls.ButtonControl"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Border x:Name="border" Background="Black">
            <TextBlock Foreground="White" Background="Brown" Name="lblCaption" TextAlignment="Center"></TextBlock>
        </Border>
    </UserControl>
    

    And then add a property to your UserControl:

    public int BorderRadius
    {
        get { return border.CornerRadius; }
        set { border.CornerRadius = value; }
    }
    

    Which allows you to set the border's CornerRadius from code.