10 ways to improve the performance of WPF applications with fine numbers

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 to eat resources,WPF The performance of the program and the hardware do have a great 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 in terms of UI design, especially custom styles and control templates, Really gives developers a lot of flexibility.

The main factor in rendering a WPF program is the amount of pixels it contains, andWPF uses Microsoft DirectX to render on the program's running hardware, so if your machine has a discrete graphics card, run WPF The program will be more fluid. In addition to improving the hardware configuration, let's look at the ten soft methods that 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 need to the value of the Bitmapscalingmode property is 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 . 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 FlowDocument the TextBlock element is used in the.

<FlowDocument>    <Paragraph>      <textblock>some text</textblock>    </paragraph >  </FlowDocument>

In addition to the above, we can rewrite the XAML content as follows, theRun 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 a Label control that, 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, It is discarded and recreated during data binding. 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&gt ;</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 display of items in a combo box 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 this 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 corresponding control to True, for example, theListbox is often used to bind large datasets, which are UI Important candidates for virtualization, other controls that are appropriate for UI virtualization include 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 lazy scrolling ( Deferred scrolling) property enhances the user experience. All you need to do is set the isdeferredscrollingenabled attached property to True.

6. increase startup time with font cache service

Font data can be shared between WPF applications, implemented through a Windows service called Presentationfontcache Services, with windows Auto-start.

You can find this service in the "Services" section of the Control Panel (or enter services.mscin 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 Storyboradand 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.

intDisplaytier = (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 with fine numbers

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.