Enable Button on valid TextBox
In WPF, I would like to have TextBox and Button. Button should be ena开发者_运维技巧bled only if the length of the text in TextBox is 10.
I am trying to do this using Binding, but it doesn't fire IsValid
property reads as I type in the TextBox.
How can this be done?
If you have just this dependency and one value for which it is valid you can use a style:
<TextBox Name="tbTest"/>
<Button Content="Do Stuff">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="IsEnabled" Value="False"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=tbTest, Path=Text.Length}" Value="10">
<Setter Property="IsEnabled" Value="true"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Otherwise you should define a ValidationRule
which should be added to the Text-binding. Then you can use code-behind to check if it is valid or bind the IsEnabled
property to Validation.HasError
(using a ValueConverter
to invert the boolean).
You have a number of ways to do it.
For example you can use Binding converter:
<TextBox>
<Binding Path="Text" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<WpfApplication1:MyValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox>
<Button>
<Button.IsEnabled>
<Binding ElementName="TB" Path="(Validation.HasError)">
<Binding.Converter>
<WpfApplication1:TrueToFalseConverter/>
</Binding.Converter>
</Binding>
</Button.IsEnabled>
</Button>
public class TrueToFalseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return !(bool) value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return !(bool)value;
}
}
public class MyValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
return new ValidationResult((value as string).Length == 10, null);
}
}
Or (I'd recommend it) you can use commands and CanExecute
:
<Button Command="{Binding Path=MyCommand}" />
<TextBox Text="{Binding Path=Text, UpdateSourceTrigger=PropertyChanged}" />
public class MainWindowViewModel
{
public RelayCommand MyCommand { get; private set; }
public string Text { get; set; }
public MainWindowViewModel()
{
Text = "";
MyCommand = new RelayCommand(MyAction, CanExecute);
}
private bool CanExecute(object x)
{
return Text.Length == 10;
}
....
}
if the length of the text in TextBox is 10 or more than 10
Try This
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (textBox1.Text.Length >= 10)
button1.IsEnabled = true;
else
button1.IsEnabled = false;
}
this not the best idea but it is useful : you can use TextChanged
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (textBox1.Text.Length == 10)
button1.IsEnabled = true;
else
button1.IsEnabled = false;
}
精彩评论