簡體   English   中英

驗證 WPF 時禁用按鈕

[英]Disable button when validating WPF

我對屬性進行了規則驗證。 我想要的是,當條件不滿足時,應該禁用保存按鈕。 我該怎么做? 這就是它的外觀: 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>

您可以將按鈕的 IsEnabled 綁定到一個屬性,一個 bool propfull(編寫 propfull 選項卡選項卡,它會在 Visual Studio 中為您寫出來)。

或者,您可以在按鈕上使用 MultiDataTrigger 並綁定要驗證的文本框的所有 HasError 屬性。

或者,如果您使用命令,則可以使用它的 can execute 屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM