C# 如何将RowValidationErrorTemplate动态添加到数据网格?
我想使用C代码(即不在XAML中)将RowValidationErrorTemplate添加到数据网格中。 相应的XAML:C# 如何将RowValidationErrorTemplate动态添加到数据网格?,c#,wpf,wpfdatagrid,C#,Wpf,Wpfdatagrid,我想使用C代码(即不在XAML中)将RowValidationErrorTemplate添加到数据网格中。 相应的XAML: <DataGrid.RowValidationErrorTemplate> <ControlTemplate> <Grid Margin="0,-2,0,-2" ToolTip="{Binding RelativeSource={RelativeSource FindAncestor, A
<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>
如果你想知道这背后的原因,以下是我的情况:
我将EventHandler移动到基类,现在我正在寻找将验证代码的最后一部分移动到基类的方法。您可以使用
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;
string xaml=”“;
dataGrid.RowValidationErrorTemplate=System.Windows.Markup.XamlReader.Parse(xaml)作为控制模板;
为什么不创建您自己的从DataGrid继承的控件?@Isma,您是说XAML继承吗?这是一个非常复杂的话题,我尽量避免。这就是为什么我的UserControls继承自.cs代码。非常感谢。编辑控制模板的唯一方法是使用XAML格式吗?是否没有与XAML对应的类和属性?是的,有FrameworkElementFactory,但使用它是一种不推荐的方式,可以按照MSDN上的说明以编程方式创建模板:谢谢。他们说“推荐的以编程方式创建模板的方法是使用XamlReader类的load方法从字符串或内存流中加载XAML。”