10 ways to improve the performance of WPF applications (forwarding)

Source: Internet
Author: User

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 improvements are not done overnight, and good design can eliminate performance-related issues, such as constructing objects at run time that can 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.

The main factor in rendering a WPF program is the amount of pixels it contains, and WPF uses Microsoft's DirectX to render on the program's running hardware, so if your machine has a discrete graphics card, running the 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, and you need to set the value of the Bitmapscalingmode property to Lowquality. This will use 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. Use 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 TextBlock elements 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 the overhead of rendering is much smaller.

<flowdocument><paragraph><run>some text</run></paragraph></flowdocument>

A similar example is the use of the content property of the label control, which, if it is not updated more than once in its lifetime, and is a string, the data binding process can hinder the performance of the program because the content is a string that is discarded during data binding and recreated. In this case, it is more efficient to use TextBlock to bind data to the Text property.

Unnecessary elements in the visual tree can also slow down the WPF program, and you might want to optimize the default control template in combination with layout.

3, increase the use of static resources

A static resource is a predefined resource that can be connected to a XAML property, which is similar to a compile-time binding and does not affect performance, and on the other hand, dynamic resources involve run-time lookups and the construction of objects, which can affect 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}"            Stroke= "{x:null}"            horizontalalignment= "Stretch" x:name= "ellipse"/>             <contentpresenter Horizontalalignment= "Center" verticalalignment= "center"/>                 <ellipse stroke= "{x:null}" margin= "2,3,4,5" >                   <Ellipse.Fill>                     <lineargradientbrush endpoint= "0.5,1" startpoint= "0.5,0" >                   < GradientStop color= "#FFFBFAFA" offset= "0"/>                  <gradientstop color= "#1DFFFFFF" offset= "1"/>             </ lineargradientbrush>           </Ellipse.Fill>         </Ellipse>       </grid></ Controltemplate>

4. When you want to display large data, use UI-virtualized controls

Imagine a combo box that is bound to a large number of rows, 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, which is called UI virtualization, It will only display the required container in the production project within its visible scope.

To achieve this effect, you need to set the Isvirtualizing property of the 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. Use 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. Increase startup time with font cache service

The font data can be shared between WPF applications, implemented through a Windows service called Presentationfontcache Services, which automatically starts 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 using Unload events

Animations will certainly occupy a certain amount of resources, if the disposition of improper, will consume more resources, if you think they are useless, you should consider how to deal with them, if not, you have to wait until the lovely garbage collector to reclaim resources.

For example, suppose you want to delete a Storyborad and use the Storyborad Remove method in the Unload event, the following example is from MSDN.

<eventtrigger routedevent= "page.unloaded" >          <EventTrigger.Actions>            <removestoryboard Beginstoryboardname= "Mybeginstoryboard"/>          </EventTrigger.Actions>  </EventTrigger>

8. Improve performance with container recycling

You can improve performance by recycling the 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 capability

Using the Rendercapability.tier property to determine whether the machine supports hardware acceleration, or some hardware acceleration, and doubts that there is no hardware acceleration, the following code shows you how to check tier.

int displaytier = (System.Windows.Media.RenderCapability.Tier > +)    if (Displaytier = = 0)  {     //no Hardware Acceleration  }  Else if (displaytier = = 1)  {     //partial hardware acceleration  }  Else  {     //supports hardware acceleration  }

Once you've identified it, you can selectively select features that work well on the user's hardware.

10. Analyzing WPF programs using the 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, such as Snoop,wpfperf,perforator and visual Profiler, in the market, where Perforator and visual Profiler is part of the WPF performance Suite, and to understand the use of these tools, go to their project homepage.

10 ways to improve the performance of WPF applications (forwarding)

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.