Click here to Skip to main content
11,798,866 members (51,832 online)
Rate this: bad
Please Sign up or sign in to vote.
I have created user control which contain TextBox and PasswordBox.

        <Converters:BoolToVisibilityConverter x:Key="boolToVisConverter" />
        <Converters:BoolToVisibilityConverter x:Key="boolToVisConverterReverse" />
    <Grid x:Name="LayoutRoot" removed="White" Width="Auto">
        <StackPanel Margin="5,5,5,5">
            <TextBox Text="{Binding TextValue}" Visibility="{Binding IsTextBox,Converter={StaticResource boolToVisConverter}}" BorderBrush="Green" />
            <PasswordBox Password="{Binding TextValue}" Visibility="{Binding IsTextBox,Converter={StaticResource boolToVisConverterReverse}}" BorderBrush="Red" />


public partial class RestrictedBox : UserControl
        public RestrictedBox()
        public string TextValue
            get { return (string)GetValue(TextValueProperty); }
            set { SetValue(TextValueProperty, value); }
        public static readonly DependencyProperty TextValueProperty = DependencyProperty.Register("TextValue", typeof(string), typeof(RestrictedBox), new PropertyMetadata(default(string)));
        public bool IsTextBox
            get { return (bool)GetValue(IsTextBoxProperty); }
            set { SetValue(IsTextBoxProperty, value); }
        public static readonly DependencyProperty IsTextBoxProperty = DependencyProperty.Register("IsTextBox", typeof(bool), typeof(RestrictedBox), new PropertyMetadata(default(bool)));

Now i added above User Control to my LoginView.xaml page
<control:RestrictedBox TextValue="Imdadhusen" IsTextBox="True"   />

Now i run the application but the TextValue = "Imdadhusen" is not bind with my text box and the second property IsTextBox is set to True that means it will automatically hide Passwordbox else Textbox.

Any help would be appreciated!

Thanks, Imdadhusen
Posted 27-Feb-12 1:42am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

UserControls do not register themselves as the data context automatically so the binding inside the user control won't have anything to bind to.

I have added following line my UserControl codebehind to enable default binding.

public RestrictedBox()
     this.DataContext = this;


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 CPallini 465
1 OriginalGriff 378
2 Maciej Los 305
3 Richard MacCutchan 281
4 phil.o 244
0 OriginalGriff 2,270
1 Maciej Los 1,810
2 KrunalRohit 1,496
3 CPallini 1,425
4 Richard MacCutchan 1,109

Advertise | Privacy | Mobile
Web03 | 2.8.151002.1 | Last Updated 27 Feb 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100