无法从主视图绑定UserControl [英] Not able to bind UserControl from main View

查看:115
本文介绍了无法从主视图绑定UserControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了包含TextBox和PasswordBox的用户控件.

RestrictedBox.xaml

I have created user control which contain TextBox and PasswordBox.

RestrictedBox.xaml

<UserControl.Resources>
        <Converters:BoolToVisibilityConverter x:Key="boolToVisConverter" />
        <Converters:BoolToVisibilityConverter x:Key="boolToVisConverterReverse" />
    </UserControl.Resources>
    <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" />
        </StackPanel>
    </Grid>



RestrictedBox.xaml.cs



RestrictedBox.xaml.cs

public partial class RestrictedBox : UserControl
    {
        public RestrictedBox()
        {
            InitializeComponent();
        }

        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)));
    }



现在,我在用户控件上方添加到了 LoginView.xaml 页面



Now i added above User Control to my LoginView.xaml page

<control:RestrictedBox TextValue="Imdadhusen" IsTextBox="True"   />



现在,我运行该应用程序,但TextValue ="Imdadhusen"未与我的文本框绑定,并且第二个属性IsTextBox设置为True,这意味着它将自动隐藏Passwordbox,否则将隐藏Textbox.


任何帮助将不胜感激!

谢谢,Imdadhusen



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

推荐答案

UserControl不会自动将其自身注册为数据上下文,因此用户控件内的绑定没有任何要绑定的内容.

我在用户控件代码的后面添加了以下行,以启用默认绑定.

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()
{
     InitializeComponent();
     this.DataContext = this;
}



谢谢,
Imdadhusen



Thanks,
Imdadhusen


这篇关于无法从主视图绑定UserControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆