Istvan Heckl
Istvan Heckl

Reputation: 1101

How to use StaticResource in DataGrid.RowValidationErrorTemplate?

In a DataGrid I have RowValidationErrorTemplate which works perfectly. I have several DataGrid in my application and I want to use the same ControlTemplate. How can I do it?

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

Upvotes: 1

Views: 125

Answers (1)

You should define the template in Window.Resources or Application.Resources in App.xaml or in resource dictionary, give it an x:Name and apply it to a DataGrid you wish:

<Window....>
    <Window.Resources>
        <ControlTemplate x:Name="DataGridRowErrorTemplate">
            //Your template
        </ControlTemplate>
    </Window.Resources
</Window>

Or, especially if you have several windows where there are DataGrids to which you want to apply a template, your can add it to App.xaml file Application.Resources:

<Application...>
    <Application.Resources>
        <ControlTemplate x:Name="DataGridRowErrorTemplate">
            //Your template
        </ControlTemplate>
    <Application.Resources>
</Application>

Or you add a resource file to your project: right-click on the project in Solution Explored=>Add=>WPF=>Resource dictionary, give it a name (e.g. MyDictionary), put your template in it and then add to App.xaml

<Application...>
    <Application.Resources>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    <Application.Resources>
</Application>

Then in DataGrid definition you do just:

<DataGrid RowValidationErrorTemplate={StaticResource DataGridRowErrorTemplate}>

</DataGrid>

Upvotes: 2

Related Questions