Bassem
Bassem

Reputation: 820

How to dynamically add RowValidationErrorTemplate to a DataGrid?

I want to add a RowValidationErrorTemplate to a DataGrid using C# code (i.e. not in XAML). The corresponding 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:

  1. I have several UserControls that inherit from a .cs code.
  2. Each UserControl contains a DataGrid that has: RowValidationErrorTemplate, EventHandlers, Validation Methods, ... etc.

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.

Upvotes: 0

Views: 107

Answers (1)

mm8
mm8

Reputation: 169270

You could use the XamlReader.Parse method to dynamically create a 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;

Upvotes: 1

Related Questions