56

I have the following style but i need to make it programmatically:

<xcdg:DataGridControl MinHeight="300" 
                      Name="listViewUnallocated" 
                      ItemsSource="{Binding Source={StaticResource
                                         cvs_unallocatedTerminals}}"
                      AllowDrop="True" 
                      Drop="Grid_Drop" 
                      MouseMove="Grid_MouseMove" 
                      KeyUp="listViewUnallocated_KeyUp"
                      MouseDoubleClick="gridUnallocated_MouseDoubleClick"
                      ReadOnly="True"
                      DockPanel.Dock="Top">
    <xcdg:DataGridControl.Resources>
        <Style TargetType="{x:Type xcdg:DataRow}" x:Name="selectedStyleTrigger">
            <Style.Triggers>
                <DataTrigger Binding="{Binding TerminalId}" Value="72948028">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </xcdg:DataGridControl.Resources>
Cœur
  • 37,241
  • 25
  • 195
  • 267
user384080
  • 4,576
  • 15
  • 64
  • 96

3 Answers3

66

In the code-behind file of the control, try:

this.Style = Resources["ResourceName"] as Style;
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • 6
    What's the difference between FindResource("ResourceName") and Resources["ResourceName"]? – SepehrM Sep 03 '14 at 11:23
  • 6
    With this I could not find the style on a Window's constructor, but with the `FindResource`method I could. (It's an abstract class, inherited in several places and with no defined XAML.) – ANeves Jan 08 '15 at 19:24
  • 1
    I think it's no good idea to do this. If this is really to be done, then I would at least add a comment like: ``in the XAML file. Otherwise I would implement it completely in code behind. – marsh-wiggle Jul 21 '19 at 19:16
54

Set x:Key in XAML & in code-behind use:

something.Style = (Style) FindResource("YourResourceKey");
Mangesh
  • 5,491
  • 5
  • 48
  • 71
21

Hi we can set style programmatically like this.

Style rowStyle = new Style(typeof(DataGridRow));

DataTrigger dataTrigger = new DataTrigger("TerminalId");
Binding binding = new Binding();
dataTrigger.Binding = binding;
dataTrigger.Value = 72948028;

Setter setter = new Setter(DataGridRow.BackgroundProperty, Brushes.Red);

dataTrigger.Setters.Add(setter);

rowStyle.Triggers.Add(dataTrigger);
listViewUnallocated.RowStyle = rowStyle;
Vishwash Roy
  • 281
  • 2
  • 7