Search code examples
c#wpfxaml

How to Convert XAML to c#?


I'm using accordion control.

<dxa:AccordionControl.Resources>
    <Style TargetType="dxa:AccordionItem">
        <Setter Property="Foreground" Value="Orange"/>
        <Style.Triggers>
            <Trigger Property="IsMouseOverHeader" Value="True">
                <Setter Property="Foreground" Value="black"/>
            </Trigger>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="Black"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</dxa:AccordionControl.Resources>

But I don't use it anymore ↑ because I changed the contents of the item dynamically.

Setter setter = new Setter();
           Style style2 = new Style();

           style2.TargetType = new AccordionItem().GetType();
           setter.Property = AccordionItem.ForegroundProperty;
           setter.Value = Brushes.Red;
           style2.Setters.Add(setter);

           ResourceDictionary resourceDictionary = new ResourceDictionary();
           resourceDictionary.Add(style2.TargetType, style2);

          //Trigger trigger = new Trigger();
          //trigger.Property = AccordionItem.IsMouseOverHeaderProperty;
          //trigger.Value = true;


           accordionControlHistoryMenu.Resources = resourceDictionary;


How Can I express it this xamlcode convert xaml to C# source?


Solution

  • You don't need to store the style in a ResourceDictionary, just assign it directly:

    Xaml:
    <dxa:AccordionControl.Resources x:Name="myControl">
    
    Code:
    myControl.Style = style2;
    

    While this answers your question, it's almost never the correct way to do this. Your styles should be binding to dynamic data that your view model layer is creating.