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