我希望我的登录按钮禁用,直到用户在Windows Phone的用户名和密码字段中输入至少一个字符。我做了什么在转换器中定义了两个依赖属性并检查它们的值,但所有这些在这里不起作用的是我的转换器代码。
public class LoginEnableConverter : DependencyObject,IValueConverter
{
public static DependencyProperty dep_username = DependencyProperty.Register("Dep_UserName", typeof(string), typeof(LoginEnableConverter), new PropertyMetadata(null));
public string Dep_UserName
{
get { return (string)GetValue(dep_username); }
set { SetValue(dep_username, value); }
}
public static DependencyProperty dep_password = DependencyProperty.Register("Dep_Password", typeof(string), typeof(LoginEnableConverter), new PropertyMetadata(null));
public string Dep_Password
{
get { return (string)GetValue(dep_password); }
set { SetValue(dep_password, value); }
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return !string.IsNullOrEmpty(Dep_UserName) && !string.IsNullOrEmpty(Dep_Password);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return !string.IsNullOrEmpty(Dep_UserName) && !string.IsNullOrEmpty(Dep_Password);
}
}
将属性绑定到转换器
<converter:LoginEnableConverter x:Key="EnableLogin" Dep_Password="{Binding Path=DataContext.Password}" Dep_UserName="{Binding Path=DataContext.UserName}"></converter:LoginEnableConverter>
我的XAML代码
<toolkit:PhoneTextBox Grid.Column="0" Text="{Binding UserName, Mode=TwoWay}" Grid.Row="0" Margin="0,50,0,0" Background="#C9F2EE" HorizontalAlignment="Stretch" ActionIcon="/Assets/user_ic.png" FlowDirection="LeftToRight" Hint="Username" Name="txtUsername"
BorderBrush="Gray" BorderThickness="1" TextWrapping="NoWrap" VerticalAlignment="Top" Style="{StaticResource PhoneTextBoxStyle1}">
</toolkit:PhoneTextBox>
<toolkit:PhoneTextBox Grid.Column="0" Text="{Binding Password, Mode=TwoWay}" Margin="0,30,0,0" Grid.Row="1" Name="Password" Background="#C9F2EE" ActionIcon="/Assets/key_ic.png" Style="{StaticResource PhoneTextBoxStyle1}" Hint="Password"
BorderBrush="Gray" BorderThickness="1" VerticalAlignment="Top">
</toolkit:PhoneTextBox>
<Button x:Name="btnLogin" Grid.Row="3" Margin="0,40,0,0" Content="Log in" IsEnabled="{Binding Converter={StaticResource EnableLogin}}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="293" Foreground="White" Background="Gray" Height="81" Style="{StaticResource ButtonStyle3}">
</Button>
答案 0 :(得分:0)
在按钮的控件绑定中,实际上并不绑定到某个值。值转换器代码不会运行,因为没有提示它运行。相反,您需要绑定到属性值,并在例如任一框中键入字符时更改该值。
此外,查看您的依赖项属性,没有您实际调用setter的地方。这需要发生的真实位置是用于绑定用户名和密码字段的任何对象。
在任何情况下,这都不具有数据绑定是实现最终结果的适当方法的场景。您需要做的是绑定到文本框上的TextChanged
事件,并将启用/禁用逻辑移动到事件处理程序的代码中。为此,请将以下属性添加到每个文本框中:TextChanged="OnUserOrPasswordTextChange"
然后,在页面的代码隐藏中,
private void OnUserOrPasswordTextChange(object sender, TextChangedEventArgs e)
{
btnLogin.IsEnabled = !string.IsNullOrEmpty(txtUsername.Text) && !string.IsNullOrEmpty(Password.Text);
}
请注意,我没有测试,但您应该了解我的建议。
有关数据绑定的更多阅读,请参阅this article关于数据绑定以了解这些概念。密切关注他们在代码隐藏中所做的工作。