wpf 验证错误时禁用按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6509541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:57:00  来源:igfitidea点击:

Disabling button on Validation error

wpfxamlvalidation

提问by anderi

I have couple of textboxes with custom validators:
(I don't mind if "wrong" data is sent back to object (the property is string), I just need to prevent the functionality of a button if there is an error, so if the binding is not the right place for that kind of validation please tell. I just like the Validation.ErrorTemplate support that i can use)

我有几个带有自定义验证器的文本框:(
我不介意是否将“错误”数据发送回对象(属性是字符串),如果出现错误,我只需要阻止按钮的功能,所以如果绑定不是这种验证的正确位置,请告诉我。我只是喜欢我可以使用的 Validation.ErrorTemplate 支持)

<ControlTemplate x:Key="validator" >
    <DockPanel LastChildFill="True">
       <TextBlock DockPanel.Dock="Right" Foreground="Red" FontSize="12pt">!</TextBlock>
       <Border BorderBrush="Red" BorderThickness="1.0">
            <AdornedElementPlaceholder />
       </Border>
    </DockPanel>
</ControlTemplate>

<TextBox Height="23" Width="150"  TextWrapping="Wrap"
         Validation.ErrorTemplate="{StaticResource validator}">
         <TextBox.Text>
            <Binding Path="StringProperty" UpdateSourceTrigger="LostFocus">
               <Binding.ValidationRules>
                   <local:NumbersOnly/>
               </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
</TextBox>

How can I disable specific button if any of the validation error is raised?

如果引发任何验证错误,如何禁用特定按钮?

<Button Content="DO Work"  Height="57" HorizontalAlignment="Left"  Name="button1" VerticalAlignment="Top" Width="234" Click="button1_Click" />

回答by S.Mishra

You can use MultiDataTriggerproperty in Style.Triggersof Button. Let's assume that we have a TextBoxnamed "txtName". We have to disable button "btnSave" on the validation error of TextBox.

您可以MultiDataTriggerStyle.Triggersof 中使用属性Button。假设我们有一个TextBox名为“txtName”的名称。我们必须在验证错误时禁用按钮“btnSave” TextBox

Here is what you can do:

您可以执行以下操作:

<Button Content="Save" 
        Grid.Column="1"
        Grid.Row="3"
        HorizontalAlignment="Right"
        Height="23" 
        Name="btnSave" 
        Width="75"
        IsDefault="True"
        Command="{Binding SaveProtocolCommand}"
        Margin="3">
  <Button.Style>
    <Style TargetType="Button">
      <Setter Property="IsEnabled" Value="False"/>
      <Style.Triggers>
        <MultiDataTrigger>
          <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding Path=(Validation.HasError), ElementName=txtName}" Value="False"/>
          </MultiDataTrigger.Conditions>
          <Setter Property="IsEnabled" Value="True"/>
        </MultiDataTrigger>
      </Style.Triggers>
    </Style>
  </Button.Style>
</Button>

Hope this will help you.

希望这会帮助你。

回答by Saad Haffar

CanExecutein MVVM is for authorization management but people use it for validation. The best way is to do it in XAML. You will need a converter if you have multiple fields to validate (InverseAndBooleansToBooleanConverteris my implementation for multiple Booleans values). Here is how to do so:

CanExecute在 MVVM 中用于授权管理,但人们使用它进行验证。最好的方法是在 XAML 中进行。如果您有多个要验证的字段(InverseAndBooleansToBooleanConverter是我对多个布尔值的实现),您将需要一个转换器。这样做的方法如下:

XAML code(I'm sorry if the XAML code does show because I could have it appear even if I tried):

XAML 代码(如果 XAML 代码确实显示,我很抱歉,因为即使我尝试过,我也可以让它出现):

<Button Name="Button_Test" Content="Test">
    <Button.IsEnabled>
        <MultiBinding Converter="{StaticResource InverseAndBooleansToBooleanConverter}" Mode="TwoWay">
            <Binding ElementName="TextBox_Field1" Path="(Validation.HasError)" />
            <Binding ElementName="TextBox_Field2" Path="(Validation.HasError)" />
            <Binding ElementName="TextBox_Field3" Path="(Validation.HasError)" />
        </MultiBinding>
    </Button.IsEnabled>
</Button>

The converter

转换器

public class InverseAndBooleansToBooleanConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (values.LongLength > 0)
        {
            foreach (var value in values)
            {
                if (value is bool && (bool)value)
                {
                    return false;
                }
             }
        }    
        return true;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
            throw new NotImplementedException();
    }
}

回答by Irineu Licks Filho

Add this to your TextBlock:

将此添加到您的 TextBlock:

Validation.Error="Save_Error"

CodeBehind (xaml.cs):

代码隐藏(xaml.cs):

public partial class MyView : Window
{
    private int _noOfErrorsOnScreen = 0;

    public MyView()
    {
        InitializeComponent();
    }


    private void Save_Error(object sender, ValidationErrorEventArgs e)
    {
        if (e.Action == ValidationErrorEventAction.Added)
            _noOfErrorsOnScreen++;
        else
            _noOfErrorsOnScreen--;

        Save.IsEnabled = _noOfErrorsOnScreen > 0 ? false : true;

    }
}

回答by Kishore Kumar

回答by StepUp

If you use MVVM then just implement a method CanExecute of interface ICommand. Button doesn't become disabled when command CanExecute is false

如果您使用 MVVM,则只需实现接口的 CanExecute 方法ICommand当命令 CanExecute 为 false 时,按钮不会被禁用

If you write your logic in codebehind then just use a property of a button IsEnabled:

如果您在代码隐藏中编写逻辑,则只需使用按钮 IsEnabled 的属性:

xaml:

xml:

<Button Name=_btn/>

SomeForm.xaml.cs:

SomeForm.xaml.cs:

_btn.IsEnabled=false;