【问题标题】:Disable button when validating WPF验证 WPF 时禁用按钮
【发布时间】:2019-09-23 14:01:24
【问题描述】:

我对属性进行了规则验证。我想要的是,当条件不满足时,应该禁用保存按钮。我该怎么做?这是它的外观: image。该按钮未被禁用。

这是我的代码

public string FieldName { get; set; }
public Regex regularExpression = new Regex("^[a-zA-Z]*$");

public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{

    //var stringValue = value as string;
    if (FieldName == "Age")
        return AgeValidate(value);
    if (FieldName == "Name")
        return NameValidation(value);
    return new ValidationResult(true, null);

}


private ValidationResult NameValidation(object value)
{
    var onlyCharacters = regularExpression.IsMatch((string)value);
    if (onlyCharacters)
        return new ValidationResult(true, null);
    else
        return new ValidationResult(false, $"Only alfabetical charaters");

}

在 XAML 中:

<Label Grid.Row="0" Grid.Column="0" Margin="103,0,98,10" Content="Name : " VerticalContentAlignment="Center" HorizontalContentAlignment="Right" Grid.ColumnSpan="2"/>
<TextBox   Grid.Row="0" Grid.Column="1" x:Name="txtCourtName"  Margin="113,4,-55,6" VerticalContentAlignment="Center" HorizontalContentAlignment="Left"  Validation.ErrorTemplate="{StaticResource errorTemplate}"  >
    <TextBox.Text>
        <Binding Path="CourtName" ValidatesOnDataErrors="true" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local11:AuthValidation FieldName="Name"></local11:AuthValidation>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

按钮:

<Button Content="Save" x:Name="btnSaveCourt"  Command="{Binding SaveCourt}" Margin="2,10" Width="119"  Background="#909090" Foreground="Black" BorderBrush="White" />

还有我的错误模板:

<ControlTemplate x:Key="errorTemplate">
    <Border BorderBrush="OrangeRed" BorderThickness="2">
        <Grid>
            <AdornedElementPlaceholder>
                <TextBlock Text="{Binding [0].ErrorContent}" Foreground="OrangeRed" 
                                   VerticalAlignment="Center" HorizontalAlignment="Right"
                                   Margin="-220"
                                   >
                </TextBlock>
            </AdornedElementPlaceholder>
        </Grid>
    </Border>
</ControlTemplate>

【问题讨论】:

标签: c# .net wpf validation mvvm


【解决方案1】:

您可以将按钮的 IsEnabled 绑定到一个属性,一个 bool propfull(编写 propfull 选项卡选项卡,它会在 Visual Studio 中为您写出来)。

或者您可以在按钮上使用 MultiDataTrigger 并绑定您要验证的文本框的所有 HasError 属性。

或者如果你使用一个命令,你可以使用它的 can execute 属性。

【讨论】:

  • 永远不要尝试在 MVVM 中设置 Button.IsEnabled - 最好使用带有 CanExecute 机制的 ICommand 实现。
  • 使用 canexecute 通常会更好,但并不总是理想的。有时,您的逻辑可能不涉及用户输入或大量命令。在这种情况下,您会发现 invalidaterequerysuggested 有问题。
  • @Peregrine 它也可以在 xaml 中使用。并且它没有在 MVVM 中设置 IsEnabled,而是从 xaml 绑定到它,以防您在代码中也有一些逻辑。
猜你喜欢
  • 2011-02-02
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 2013-07-03
相关资源
最近更新 更多