C#C
C#2y ago
99 replies
Furinaxi

✅ How to get data out of a custom control?

Currently, I'm doing a custom user control for a password box with a label showcasing what to put in there.

Right now, this is the content of my user control:
<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label Content="{Binding LabelText, ElementName=root}" Height="24" Margin="0 0 0 5" Grid.Column="0"/>
        <PasswordBox Width="200" Height="24" Password="{Binding Password, ElementName=root}" Grid.Column="1"/>
    </Grid>


And this is the .cs file:
using System.Windows;
using System.Windows.Controls;

namespace WoWSpect.Components;

public partial class PasswordBoxWithLabel : UserControl
{
    public static readonly DependencyProperty LabelTextProperty = DependencyProperty.Register(
        nameof(LabelTextProperty), typeof(string), typeof(PasswordBoxWithLabel), new PropertyMetadata(string.Empty));

    public static readonly DependencyProperty PasswordProperty = DependencyProperty.Register(
        nameof(Password), typeof(string), typeof(PasswordBoxWithLabel), new PropertyMetadata(string.Empty));

    public string Password
    {
        get { return (string)GetValue(PasswordProperty); }
        set { SetValue(PasswordProperty, value); }
    }
    
    public string LabelText
    {
        get { return (string)GetValue(LabelTextProperty); }
        set { SetValue(LabelTextProperty, value); }
    }
    
    public PasswordBoxWithLabel()
    {
        InitializeComponent();
    }
}


But as soon as I use it somewhere to display something, I get this error:
System.Windows.Markup.XamlParseException: A 'Binding' cannot be set on the 'Password' property of type 'PasswordBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

How can I fix it? I need to get the password out of the password box from my user control, but since I cannot use a property apparently, I don't know another way to do it.
Was this page helpful?