Home > Software engineering >  I write some codes to make a user control in WPF application, but corner radius is not working [clos
I write some codes to make a user control in WPF application, but corner radius is not working [clos

Time:10-03

I'm new to WPF. I write some codes to make a user control in WPF application ? but corner radius is not working. I attached codes to this.

User Control Code

<UserControl x:Class="StoreManagementSystem.usercontrols.ModernButton"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:StoreManagementSystem.usercontrols"
         Name="newbutton"
         mc:Ignorable="d" 
         d:DesignHeight="50" d:DesignWidth="200">
<StackPanel>
    <Button Height="50">
        <Button.Resources>
            <Style TargetType="Border">
                <Setter Property="CornerRadius" Value="{Binding radius,ElementName=newButton}"/>
            </Style>
        </Button.Resources>
    </Button>
</StackPanel>

User Control CS file

namespace StoreManagementSystem.usercontrols
{
    public partial class ModernButton : UserControl
    {


        public int radius
        {
            get { return (int)GetValue(radiusProperty); }
            set { SetValue(radiusProperty, value); }
        }

        public static readonly DependencyProperty radiusProperty =
            DependencyProperty.Register("radius", typeof(int), typeof(ModernButton), new PropertyMetadata(0));

        public ModernButton()
        {
            InitializeComponent();
        }
    }
}

I tried that code and in the main window I add this control to main window and set the radius but this is not working.

CodePudding user response:

After I cleaned the solution and rebuild its start working. But previously I try to clean and rebuild it not worked. Thank you for helping.

CodePudding user response:

You binding context is not being set correctly and will be set the DataContext of the element you add the usercontrol too.

You could start by changing your constructor to this

public ModernButton()
{
   InitializeComponent();
   this.DataContext = this;
}

This will tell the UserControl to use itself as the DataContext. You then don't need to use elementname and it should bind to the DependencyProperty correctly.

<Setter Property="CornerRadius" Value="{Binding Path=radius}"/>

On a side note: The normal approach for C#/dotnet is to have properties start with capitals.

Take a look at this tutorial -> https://blog.scottlogic.com/2012/02/06/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight.html

  • Related