如何根据ValidationRule类禁用按钮?

时间:2012-01-23 18:13:02

标签: c# wpf xaml

如何根据ValidationRule类禁用WPF按钮? (下面的代码可以很好地突出显示TextBox)

<Button x:Uid="btnSave" Content="{lex:LocTextExtension Key=Save, Dict=Resources, Assembly=PreShow.Player}"   Height="23" HorizontalAlignment="Center"  Name="btnSave" VerticalAlignment="Top" Width="75" IsDefault="True">

XAML:

<Window.Resources>
        <k:PlayerConfiguration x:Key="ods"/>
        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
                <AdornedElementPlaceholder/>
            </DockPanel>
        </ControlTemplate>
        <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
              Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                              Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>




<TextBox Grid.Column="1" Height="23" HorizontalAlignment="Left" Name="textBox1"     VerticalAlignment="Top" Width="277">
   <TextBox.Text>
     <Binding Path="UserName" Source="{StaticResource ods}"  UpdateSourceTrigger="PropertyChanged" >
       <Binding.ValidationRules>
           <c:ConfigValidationRule />
             </Binding.ValidationRules>
    </Binding>
   </TextBox.Text>
</TextBox>

C#

 public class ConfigValidationRule : ValidationRule
    {
        public ConfigValidationRule()
        {
            HasError = true;
        }

        public bool HasError { set; get; }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            try
            {
                if (((string)value).Length > 0)
                {
                    HasError = false;
                    return new ValidationResult(true, null);
                }
                else
                {
                    HasError = true;
                    return new ValidationResult(false, "!");
                }
            }
            catch
            {
                HasError = true;
                return new ValidationResult(false, "!");
            }
        }
    }

有很多例子但是所有例子都没有SAVE BUTTON。

  1. http://www.codeproject.com/Articles/15239/Validation-in-Windows-Presentation-Foundation
  2. http://go.microsoft.com/fwlink/?LinkID=159972

0 个答案:

没有答案