2011-09-16 49 views
1

我有我自己的用户控制:通过验证错误

[TemplateVisualState(Name = StateValid, GroupName = GroupValidation)] 
[TemplateVisualState(Name = StateInvalidFocused, GroupName = GroupValidation)] 
[TemplateVisualState(Name = StateInvalidUnfocused, GroupName = GroupValidation)] 
public class SearchTextBoxControl : TextBox 
{ 
    // properties removed for brevity 

    public override void OnApplyTemplate() 
    { 
     base.OnApplyTemplate(); 
     this.BindingValidationError += (s, e) => UpdateValidationState(); 
     this.UpdateValidationState(); 
    } 

    public const string GroupValidation = "ValidationStates"; 
    public const string StateValid = "Valid"; 
    public const string StateInvalidFocused = "InvalidFocused"; 
    public const string StateInvalidUnfocused = "InvalidUnfocused"; 

    private void UpdateValidationState() 
    { 
     var textBox = this.GetTemplateChild("ContentTextBox"); 
     if (textBox != null) 
     { 
      VisualStateManager 
       .GoToState(textBox as Control, 
          Validation.GetErrors(this).Any() ? 
           StateInvalidUnfocused : 
           StateValid, 
          true); 
     } 
    } 
} 

和XAML:

<Style TargetType="local:SearchTextBoxControl"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="local:SearchTextBoxControl"> 
       <Grid Grid.Column="1" 
         Grid.ColumnSpan="3" 
         Grid.Row="1" 
         Margin="{TemplateBinding Margin}"> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="*" /> 
         <ColumnDefinition Width="32" /> 
        </Grid.ColumnDefinitions> 

        <TextBox x:Name="ContentTextBox" 
          Grid.ColumnSpan="2" 
          IsReadOnly="{TemplateBinding IsReadOnly}" 
          Text="{TemplateBinding Text}"> 
        </TextBox> 
        <Button Grid.Column="1" 
          Style="{StaticResource BrowseButton}" 
          Command="{TemplateBinding Command}"> 
         <ToolTipService.ToolTip> 
          <ToolTip Content="{TemplateBinding ToolTip}" /> 
         </ToolTipService.ToolTip> 
         <Image Source="../../Resources/Images/magnifier.png" 
           Style="{StaticResource BrowseButtonImage}" /> 
        </Button> 
       </Grid> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

我应该怎么做,以通过验证的错误到TextBox X:名称= “ContentTextBox”验证服务(我想在我的控制文本框中使用相同的验证错误工具提示)? 亲切的问候!

+0

反正 - 你知道答案吗? :) – Zozo

+0

不幸的是,可能没有。在WPF中,对于这样简单的事情,我会实现IDataErrorInfo,并执行ValidatesOnDataErrors事情。但我不确定Silverlight是否支持这一点,或者使用视觉状态。 – Will

回答

1

您可以实现IDataErrorInfo接口。它在ComponentModel Lib中可用。

using System.ComponentModel;

公共类SearchTextBoxControl:文本框,IDataErrorInfo的

{

#region IDataErrorInfo Members 

    public string Error 
    { 
     get { throw new NotImplementedException(); } 
    } 

    public string this[string columnName] 
    { 
     get { throw new NotImplementedException(); } 
    } 

    #endregion 
    // Your Code 

}

+0

这不完全是我所期待的,但thanx :) – Zozo