c# - WPF-文本 block /标签的数据网格行验证错误?

标签 c# wpf validation xaml datagrid

在 WPF 中,我有一个具有不同验证的 DataDrid

到目前为止,我在 DataGrid 中使用了 ToolTip 来显示错误验证:

<DataGrid.RowValidationErrorTemplate>
   <ControlTemplate>
      <Grid Margin="0,-2,0,-2" ToolTip="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}},Path=(Validation.Errors)[0].ErrorContent}">
         <Ellipse StrokeThickness="0" Fill="Red" Width="{TemplateBinding FontSize}" Height="{TemplateBinding FontSize}" />
         <TextBlock Text="!" FontSize="{TemplateBinding FontSize}" FontWeight="Bold" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" />
      </Grid>
   </ControlTemplate>
</DataGrid.RowValidationErrorTemplate>

现在客户要求在页面的不同 TextBlock/Label 中显示验证错误 - 我该怎么做?我如何在 DataGrid 之外使用:(Validation.Errors)[0].ErrorContent

最佳答案

您可能有一个类似 ValidationRules 的类,它包含一个验证函数。

由于发生了宏伟的绑定(bind),您不再需要在绑定(bind)时遵循验证。然而,这坚持控制。

您还可以在用于验证的数据网格内的控件上创建一个事件。

<DataGridTemplateColumn Header="MyValue">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Textbox Text="{Binding MyValue}" OnLeave="tb_OnLeave"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

在你身后你可以有类似的东西:

private void tb_OnLeave(object sender, EventArgs e)
{
  //sender defines your value;
  Textbox s = (Textbox)sender;

  //validate the Text property of the sender
  if(ValidationRule.ValidateTextBox(s.Text)); //true
  return;

  //set the focus on your control
  s.Focus(); 

  //set the text of your other control
  YourOtherControl.Text = string.Format("The value of textbox: {0} is not valid", s.Text);
}

这里的要点是您将不再使用 validationBinding。 我认为有一些方法可以通过绑定(bind)来做到这一点,但我在这个话题上还不够强大,无法为您提供更好的答案。

也许 RelativeSource 可以用来指向另一个控件。但正如我所说,我所知道的还不足以确定。

关于c# - WPF-文本 block /标签的数据网格行验证错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31131624/

相关文章:

c# - 使用 select 语句后将值存储在变量中

c# - 为什么默认情况下 WPF 控件不是私有(private)的?

wpf - 阻止 WPF 文本框增长

laravel - 如何在 Laravel Validator 中仅显示错误消息

Xcode - 由于解决 info.plist 和权利中的变量/占位符的奇怪问题而无法验证存档

asp.net - 用于验证 MVC 模型属性的正则表达式

c# - 在托管服务中访问上下文

c# - 获取匹配模式的行号

c# - GC.Collect() 和完成

wpf - 列表元素 WPF 之间的制表符