How to set the style programmatically

Wpf

Wpf Problem Overview


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>

Wpf Solutions


Solution 1 - Wpf

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

this.Style = Resources["ResourceName"] as Style;

Solution 2 - Wpf

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

something.Style = (Style) FindResource("YourResourceKey");

Solution 3 - Wpf

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser384080View Question on Stackoverflow
Solution 1 - WpfGrant ThomasView Answer on Stackoverflow
Solution 2 - WpfMangeshView Answer on Stackoverflow
Solution 3 - WpfVishwash RoyView Answer on Stackoverflow