开发者

why is it faster to put ressources in my APP.xaml rather than in MyClass.xaml in WPF?

开发者 https://www.devze.com 2023-03-13 07:49 出处:网络
here\'s the thing: I have a project in which my menus/ContextMenu/MenuItems are templated. so basically I have a MyMenuItem.xaml/MyMenuItem.xaml.cs file couple with my MyMenuItem.xaml file containin

here's the thing:

I have a project in which my menus/ContextMenu/MenuItems are templated.

so basically I have a MyMenuItem.xaml/MyMenuItem.xaml.cs file couple with my MyMenuItem.xaml file containing some resources + style and template.

problem: my contextMenu (quite huge I admit, but still...) took about 14sec to load (!!)

I made some profiling and discovered that this line: MyMenuItem item = new MyMenuItem(); took 65% of the UC for those 14sec. So I tried getting rid of my styles, templates and resources in MyMenuItem.xaml and indeed, I got down to 0.3sec to load the menu. So then I put those Styles/templates in App.xaml, and managed to get the design as I wanted, but with the expected performance.

my question is: how come?

how come I cannot put my menuItem styles in my MyMenuItem.xaml file and have to put them in App.xaml to get good perf? what is going on here than I do not inderstand?

going further down this road, I deduce that all my other styles for my other controls may actually have the same issue, so then I should then put all my templates/styles in App.xaml, which kind of defeats the purpose of having for each control a .xaml/.xaml.cs couple

what am I missing/doing wrong here?

edit: just in case, here is a mockup of my MyMenuItem.xaml file:

<MyMenuItem ...>
    <MyMenuItem.Resources>
        <Style x:Key="Style1" />
        <Style x:Key="Style2" />
        <Style x:Key="Style3" />
    </MyMenuItem.Resources>
    <MyMenuItem.Style>
        <Style TargetType="MenuItem">
            <Setter Property=Template>
                 <Setter.Value>
                     <ControlTemplate TargetType="MenuItem">

                     <!--here I'm using Styles 1,2 and 3-->

                     </ControlTemplate>
            </Setter.Value>
            </Setter>
        开发者_运维技巧</Style>
    </MyMenuItem.Style>
</MyMenuItem>

and the issue is with everything including in MyMenuItem.Resources (i.e: styles 1,2 and 3)


If you declare your resources at the menu level, those resources will be created for every instance of the menu. Declare it at the app level, and a single instance of the resources will be created and shared across all menus. Basically, you want to move resources as far up the logical tree as makes sense so that you maximize the sharing of those resources.

That said, 14s sounds excessive so I can only assume you've got some pretty heavy resources in there.

0

精彩评论

暂无评论...
验证码 换一张
取 消