WPF 错误模板未显示

发布于 2024-09-27 20:38:51 字数 6077 浏览 0 评论 0原文

我没有收到任何绑定错误,并且该代码在另一个地方工作。我还没有发现我现在所做的与它工作的代码有什么不同,而且代码并不多。

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>

仅当 Model.Tags 属性长于 10 个字符时,我的 ViewModel 中的“SAVE”按钮才会被激活来自用户的输入。当我输入 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!";            
        }
    }
}

ViewModel

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

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

不起作用的是带有红色椭圆的ErrorTemplate根本不显示?

更新:下面的代码在测试项目中运行。但在我的生产项目中它找不到资源???这到底是为什么?

<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>

I get no binding errors and this code works at another place. I haven't found out yet what I do now differently to the code where it works and it's not that much code.

In 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>

Below in Xaml too:

<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>

The button SAVE in my ViewModel is only activated when the Model.Tags property is longer 10 chars input from the user. The button activation/disable works fine when I enter 10,11 and then back 8 chars. All the property changes are fired.

Model:

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!";            
        }
    }
}

ViewModel:

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

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

What does not work is the ErrorTemplate with the red Ellipse is not showing at all?

UPDATE: Exactly the below code works in a TEST project. But in my productive project It does not find the Resource??? Why the heck this?

<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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情绪 2024-10-04 20:38:51

我有类似的问题。奋斗了几个小时才意识到装饰层出了问题。

我所做的是将我的控件放在里面。就是这样。由于某种原因,这个装饰层有时会消失。对于 TabControl 来说确实如此(但就我而言,这是其他原因)。

所以它应该看起来像这样

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

希望这有帮助!

I had similar problem. Fight it for hours just to realize that something was wrong with adorner layer.

What I did is put my with controls inside . And that was it. For some reason this decorator layer sometimes is gone. This is certainly true for TabControl (but in my case it was some other reason).

So it should look like this

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

Hope this helps!

后来的我们 2024-10-04 20:38:51

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

I have had a similar problem to this, it turned out not to be the template but the validation was not returning what I expected.

只为守护你 2024-10-04 20:38:51

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

The ViewModel have to implement IDataErrorInfo, not the Model. The ViewModel binds to your View as the DataContext, not the Model, so implement the interface in ViewModel and bind to corresponding properties in XAML.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文