10 tips for WPF performance improvement

Source: Internet
Author: User

"IT168 Zhuangao" WPF (Windows Presentation Foundation) applications run slowly on machines without graphics acceleration is an open secret, giving users the feeling that it is too much for resources, and that the performance of WPF programs and hardware do have a big relationship, The more high-end machine performance has the advantage.

  Program Performance improvement is not an overnight, good design can eliminate the impact of performance problems, for example, the construction of objects at run time will affect the performance of the program. While WPF provides a richer user interface through features such as enhanced navigation, you should consider whether your users really need a rich graphical interface, although WPF has such a problem, but it does give developers a lot of flexibility in UI design, especially in custom styles and control templates.     Figure 1 WPF architecture, Blue is a Windows component, Brown is the main factor for WPF components   rendering WPF programs is the amount of pixels it contains, and WPF uses Microsoft DirectX to render on the hardware that the program runs on, so If your machine has a discrete graphics card, running a WPF program will be smoother. In addition to improving the hardware configuration, let's take a look at 10 soft methods to improve the performance of WPF programs.   1, reduce bitmapscalingmode, accelerate image rendering   when you include animations in your WPF program, you can use the Bitmapscalingmode property of the Renderoptions object to reduce resource consumption, The value of the Bitmapscalingmode property needs to be set to Lowquality, which uses the acceleration algorithm to process the image instead of the default high-quality image resampling algorithm. The following code snippet shows the most basic implementation method:  renderoptions.setbitmapscalingmode (imageobject,bitmapscalingmode.lowquality);  2, Using the right elements in the right place   we need to use the right elements in the right place, and when you build the tree you should avoid using uielements as a child or nested control, the best example being FlowDocument, We often use the TextBlock element in FlowDocument.  <FlowDocument>    <Paragraph>      <textblock>some text</ textblock>    </Paragraph>  </FlowDocument>  In addition to the above, we can rewrite the XAML content as follows, The run element is not a UIElement and renders with less overhead.  <flowdocuMent>  <paragraph>    <run>some text</Run>  </ paragraph></flowdocument>  A similar example is the use of the content property of the label control, which may hinder the performance of the program if it is updated more than once in its life cycle and is a string. , because the content is a string, it is discarded during data binding and recreated. In this case, it is more efficient to use TextBlock to bind data to the Text property.   The presence of unnecessary elements in the visual tree also slows down the speed of the WPF program, and you may want to optimize the default control template in conjunction with the layout.  3, increasing the use of static resources   Static resources are predefined resources that can be connected to XAML properties, which are similar to compile-time bindings, do not affect performance, and on the other hand, dynamic resources involve runtime lookups and the construction of objects, affecting performance. However, it is also important to note that static resources need to be presented at compile time.   References to static resources can be found in the following ways: <button        template= "{StaticResource Roundbuttonwiththickedge} "         x:name=" button1 "content=" button 1 ">  </button > The following code snippet shows the definition of static resource Roundbuttonwiththickedge  <ControlTemplate       x:key= " Roundbuttonwiththickedge "       targettype=" {x:type button} ">       < grid>         <ellipse fill= "{TemplateBinding Background}"       &NBSp    stroke= "{x:null}"            horizontalalignment= "Stretch" x:name= "Ellipse" />             <contentpresenter horizontalalignment= "Center" Verticalalignment= "Center"/>                 <ellipse stroke= "{x: Null} "margin=" 2,3,4,5 ">                   <ellipse.fill>& nbsp                    <lineargradientbrush endpoint= "0.5,1" startpoint= "0.5,0" >                   <gradientstop color= "#FFFBFAFA" Offset = "0"/>                  <gradientstop color= "#1DFFFFFF" offset= "1"/&gt ;             </LinearGradientBrush>          &NBSP;&LT ;/ellipse.fill>         </ellipse>       </Grid>     </controltemplate> 4, When you want to display large data, use the UI virtualization controls   Imagine what a combo box will look like when a large number of rows are bound, which makes the item in the combo box appear very slow, because in this case the program needs to calculate the specific display location of each item, and when using WPF, you can defer the behavior, This is called UI virtualization, which only displays the containers that are needed for the production project within its visible scope.   To achieve this effect, you need to set the Isvirtualizing property of the corresponding control to true, for example, the listbox is often used to bind large datasets, which is an important candidate for UI virtualization, and other controls that are appropriate for UI virtualization include a ComboBox, ListView and TreeView.   5, using lazy scrolling to enhance the user experience   if you remember scrollable DataGrid or ListBox, they tend to degrade the performance of the entire application because it forces continuous updates when scrolling, which is the default behavior, in which case We can use the control's deferred scrolling (Deferred scrolling) property to enhance the user experience. All you need to do is set the isdeferredscrollingenabled attached property to True.   6. Use the font caching service to increase startup time   The font data can be shared between WPF applications, which is implemented through a Windows service called Presentationfontcache Services, and it starts automatically with Windows.   You can find this service in the "Services" section of the Control Panel (or enter services.msc in the "Run" box) to ensure that the service is started.   7. Uninstalling unnecessary animations   animations using unload events will definitely take up a certain amount of resources, and if you think they're useless, you should consider how to handle them if you don't, and if you don't, wait until the cute garbage collector comes back to reclaim the resources.   For example, suppose you want to delete a Storyborad, using the Storyborad Remove method in the Unload event, the following example comes from MSDN.  <eventtrigger routedevent= "page.unloaded" >          <EventTrigger.Actions>            <removestoryboard Beginstoryboardname= "Mybeginstoryboard"/>          </EventTrigger.Actions>  &LT;/EVENTTRIGGER&GT;8, using container recycling for high performance   You can improve performance by reclaiming containers that perform virtualization, and the following code snippet sets Viruatlizationmode to recycling, which allows you to get better performance. When the user scrolls or arrives at another project, it forces the container object to be reused.   settingvirtualizingstackpanel.virtualizationmode= "Recycling"  9, predictive image rendering capabilities   Using the Rendercapability.tier property to determine whether the machine supports hardware acceleration, or part of the hardware acceleration, doubts that there is no hardware acceleration, the following code shows how you want to check the Tier int displaytier= ( System.windows.media.rendercapability.tier>     if (displaytier== 0)   {      No hardware acceleration }  else if (displaytier = = 1)   {     //partial hardware Accelera tion }  else  {     //supports hardware acceleration } was determined, You can selectively select features that work well on user hardware   10, analyzing WPF programs with WPF Profiling Tools   Analyzing WPF programs is an important step in understanding their behavior, and there are a number of ready-made WPF program analysis tools in the market, such as Snoop,Wpfperf,perforator and Visual Profiler, where Perforator and visual Profiler are part of the WPF Performance Suite, to learn about the use of these tools, go to their project home page

10 tips for WPF performance improvement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.