Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Adding style resource without key in code behind

Tags:

wpf

I'm generating a xaml from the code behind of a WPF application and want to add styles to the generated xaml. I'm using a resource dictionary to store the styling info which my app will access and apply to the appropriate elements in the generated xaml based on keys in the resource dictionary. Now I want to apply a specific style to all textboxes in the generated xaml. What I'm trying to do is to create this style in the resource dictionary without a key and I want to add this style resource to the resources of the generated xaml. I can't seem to find a way to add a particular resource to the resource dictionary of this generated xaml without a key. My questions is, is it possible to do so, i.e. add a resource to the resource dictionary of a usercontrol (or window etc.) without a key for that resource?

For example, here is the XAML I want to generate:

<UserControl>
    <UserControl.Resources>
        <Style TargetType="{x:Type TextBox}">
            <!--The TextBox style-->
        </Style>
    </UserControl.Resources>
</UserControl>

Thanks!

like image 343
Duke Cyrillus Avatar asked May 31 '12 13:05

Duke Cyrillus


1 Answers

So, I found a way to do this. While adding to the resources of the generated xaml instead of specifying a string key, I used typeof(TextBox) and that seemed to work.

UserControl.Resources.Add(typeof(TextBox), styleDictionary["TextBoxStyleKey"]);

This results in:

<UserControl.Resources>
    <Style TargetType="TextBox" x:Key="{x:Type TextBox}">
        <!--The Style-->
    </Style>
</UserControl.Resources>

Is there a better way(or any other way) of doing this?

like image 144
Duke Cyrillus Avatar answered Oct 13 '22 10:10

Duke Cyrillus