启用有效文本框上的按钮

本文关键字:按钮 有效 文本 启用 | 更新日期: 2023-09-27 17:57:35

在WPF中,我希望有TextBox和Button。仅当文本框中的文本长度为 10 时,才应启用按钮。

我正在尝试使用绑定执行此操作,但是当我在文本框中键入时,它不会触发IsValid属性读取。

如何做到这一点?

启用有效文本框上的按钮

如果您只有此依赖项和一个有效的值,则可以使用样式:

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

否则,应定义应添加到文本绑定的ValidationRule。然后,可以使用代码隐藏来检查它是否有效,或者将 IsEnabled 属性绑定到Validation.HasError(使用 ValueConverter 反转布尔值(。

你有很多方法可以做到这一点。

例如,您可以使用绑定转换器:

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

或者(我推荐它(您可以使用命令并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;
    }
    ....
}

如果文本框中文本的长度为 10 或大于 10

试试这个

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (textBox1.Text.Length >= 10)
            button1.IsEnabled = true;
        else
            button1.IsEnabled = false;
    }
这不是

最好的主意,但它很有用:您可以使用TextChanged

   private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (textBox1.Text.Length == 10)
            button1.IsEnabled = true;
        else
            button1.IsEnabled = false;
    }