WPF错误模板未显示

时间:2010-10-19 22:02:53

标签: wpf xaml templates mvvm idataerrorinfo

我没有绑定错误,此代码在另一个地方工作。我还没有发现我现在做的与它工作的代码有什么不同,而且代码不是那么多。

UserControl.Resource:

<Style TargetType="TextBox">
  <Setter Property="BorderBrush" Value="DarkBlue"/>
  <Setter Property="BorderThickness" Value="1"/>
  <Setter Property="Margin" Value="0,1,0,1"/>
  <Setter Property="Validation.ErrorTemplate">
    <Setter.Value>
      <ControlTemplate>
        <StackPanel Orientation="Horizontal">
          <AdornedElementPlaceholder/>
          <Grid Margin="2,0,0,0">
            <Ellipse Width="20" Height="20" Fill="Red"/>
            <TextBlock Foreground="White" Text="X" FontWeight="Bold"
                       HorizontalAlignment="Center" VerticalAlignment="Center"/>
          </Grid>
        </StackPanel>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
  <Style.Triggers>
    <Trigger Property="Validation.HasError" Value="True">
      <Setter Property="ToolTip"
              Value="{Binding RelativeSource={RelativeSource Self},
                  Path=(Validation.Errors)[0].ErrorContent}"/>
    </Trigger>
  </Style.Triggers>
</Style>

下面也是Xaml:

<TextBlock Height="23" HorizontalAlignment="Left" Margin="22,90,0,0"
           Text="Keywords" VerticalAlignment="Top"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="22,108,0,0"
         VerticalAlignment="Top" Width="244">
  <Binding Path="Tags" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
    <Binding.ValidationRules>
      <DataErrorValidationRule ValidatesOnTargetUpdated="False"/>
    </Binding.ValidationRules>
  </Binding>
</TextBox>

我的ViewModel中的按钮SAVE仅在Model.Tags属性从用户输入10个字符时激活。当我输入10,11然后返回8个字符时,按钮激活/禁用工作正常。所有属性更改都会被触发。

模型

namespace TBM.Model
{
    public class Document : EntityBase , IDataErrorInfo
    {
        public int Id { get; set; }
        public string DocumentName { get; set; }
        public string Tags { get; set; }
        public byte[] DocumentData { get; set; }
        public int PeriodId { get; set; }

        string IDataErrorInfo.Error { get { return null; } }

        string IDataErrorInfo.this[string propertyName]
        {
            get { return this.GetValidationError(propertyName); }
        }

        public bool IsValid
        {
            get
            {
                foreach (string property in ValidatedProperties)
                    if (GetValidationError(property) != null)
                        return false;

                return true;
            }
        }

        static readonly string[] ValidatedProperties = { "Tags", };

        private string GetValidationError(string propertyName)
        {
            if (Array.IndexOf(ValidatedProperties, propertyName) < 0)
                return null;

            string error = null;

            switch (propertyName)
            {               
                case "Tags": error = this.IsTagsEmpty(Tags); break;

                default:
                    Debug.Fail("Unexpected property being validated on Document: " + propertyName);
                    break;
            }
            return error;
        }  

        private string IsTagsEmpty(string value)
        {
            if (value != null && value.Trim().Length >= 10)
                return null;
            else
               return "The keywords must have at least 10 chars!";            
        }
    }
}

视图模型

 public RelayCommand SaveDocumentCommand
 {
     get { return _saveDocumentCommand ?? (_saveDocumentCommand =
         new RelayCommand(() => SaveDocument(),() => CanSaveDocument())); }
     }

     private bool CanSaveDocument()
     {
         return _document.IsValid;
     }
//...

什么不起作用是没有显示红色Ellipse的ErrorTemplate?

更新:以下代码在TEST项目中正常工作。但在我的生产项目中它没有找到资源???为什么这样呢?

<TextBlock Height="23" HorizontalAlignment="Left" Margin="22,89,0,0"
           Text="Keywords" VerticalAlignment="Top"/>
  <TextBox Style="{StaticResource bla}" Height="23" HorizontalAlignment="Left"
           Margin="22,109,0,0" VerticalAlignment="Top" Width="244">
    <Binding Path="Tags" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
      <Binding.ValidationRules>
        <DataErrorValidationRule ValidatesOnTargetUpdated="False"
                                 ValidationStep="UpdatedValue"/>
      </Binding.ValidationRules>
    </Binding>
  </TextBox>

<UserControl.Resources>
  <Style x:Name="bla" TargetType="TextBox">
    <Setter Property="BorderBrush" Value="DarkBlue"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="Margin" Value="0,1,0,1"/>
    <Setter Property="Validation.ErrorTemplate">
      <Setter.Value>
        <ControlTemplate>
          <StackPanel Orientation="Horizontal">                          
            <AdornedElementPlaceholder/>
            <Grid Margin="2,0,0,0">
              <Ellipse Width="20" Height="20" Fill="Red"/>
              <TextBlock Foreground="White" Text="X" FontWeight="Bold"
                         HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Grid>
          </StackPanel>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
    <Style.Triggers>
      <Trigger Property="Validation.HasError" Value="True">
        <Setter Property="ToolTip"
                Value="{Binding RelativeSource={RelativeSource Self},
                    Path=(Validation.Errors)[0].ErrorContent}"/>
      </Trigger>
    </Style.Triggers>
  </Style>
</UserControl.Resources>

3 个答案:

答案 0 :(得分:10)

我有类似的问题。为了意识到装饰层出了问题,打了好几个小时。

我所做的就是将控件放在里面。就是这样。由于某种原因,这个装饰层有时会消失。对于TabControl来说肯定是这样(但在我的情况下,这是另一个原因)。

所以看起来应该是这样的

<AdornerDecorator>
  <Grid>
    <TextBox .../>
  </Grid>
</AdornerDecorator>

希望这有帮助!

答案 1 :(得分:0)

我遇到了类似的问题,结果证明不是模板,但验证没有返回我的预期。

答案 2 :(得分:0)

ViewModel必须实现IDataErrorInfo,而不是Model。 ViewModel将您的View绑定为DataContext,而不是Model,因此在ViewModel中实现接口并绑定到XAML中的相应属性。