Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

wpf - Disabling button on Validation error

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)

<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" />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use MultiDataTrigger property in Style.Triggers of Button. Let's assume that we have a TextBox named "txtName". We have to disable button "btnSave" on the validation error of 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...