[英]How to dynamically add RowValidationErrorTemplate to a DataGrid?
I want to add a RowValidationErrorTemplate to a DataGrid using C# code (ie not in XAML). 我想使用C#代码(即不在XAML中)向数据网格添加RowValidationErrorTemplate。 The corresponding XAML: 相应的XAML:
<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" />
</Grid>
</ControlTemplate>
</DataGrid.RowValidationErrorTemplate>
If you wonder the reason behind this, here is my situation: 如果您想知道背后的原因,这是我的情况:
I moved the EventHandlers to the base class, now I'm looking for a way to move the last part of my validation code to the base class. 我将EventHandlers移至基类,现在我正在寻找一种将验证代码的最后一部分移至基类的方法。
You could use the XamlReader.Parse
method to dynamically create a ControlTemplate
: 您可以使用XamlReader.Parse
方法动态创建ControlTemplate
:
string xaml = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"><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\" /></Grid></ControlTemplate>";
dataGrid.RowValidationErrorTemplate = System.Windows.Markup.XamlReader.Parse(xaml) as ControlTemplate;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.