gpt4 book ai didi

mvvm - 无法从主视图绑定(bind) UserControl

转载 作者:行者123 更新时间:2023-12-05 00:56:35 25 4
gpt4 key购买 nike

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

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

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 页面

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

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

如有任何帮助,我们将不胜感激!

谢谢,伊姆达胡森

最佳答案

请设置您的 DataContext,因为在用户控件中它不理解 DataContext。因此,请在您的构造函数中尝试这样做。

 this.DataContext = this;

也许这对你有帮助...

关于mvvm - 无法从主视图绑定(bind) UserControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9464493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com