Search code examples
wpfstyleswpfdatagrid

Style CustomWpfDataGrid in code?


I am trying to set the style in code but have been unable to do,

in xaml

<Style x:Key="DataGridStyle1" TargetType="{x:Type DataGrid}">
    <Setter Property="Template" Value="{DynamicResource DataGridControlTemplate1}"/>
</Style>

<Style x:Key="DataGridStyle2" TargetType="{x:Type DataGrid}">
     <Setter Property="Background" Value="AntiqueWhite"/>
</Style>

this is the CustomControl:

public class CustomDataGrids : DataGrid
{
    public CustomDataGrids()
    {
        ResourceDictionary res = Application.LoadComponent(new Uri("CustomDataGridStyle.xaml", UriKind.Relative)) as ResourceDictionary;
        this.Style = (Style)res["DataGridStyle1"];
        this.ColumnHeaderStyle = (Style)res["ColumnHeaderStyle1"];
    }
}

when Style=DataGridStyle2 it works perfect,but when Style=DataGridStyle1,it dosen't work,, any ideas?


Solution

  • i guess The problem is the Template,so i had to do this:

    This.Template=(System.Windows.Controls.ControlTemplate)res["DataGridControlTemplate1"];