Чем wpf отличается от windows forms

от admin

What is the difference between WPF and WinForms?

I am programming simple Windows apps. I don’t need DB support. Why would I use WPF instead of WinForms?

8 Answers 8

One obvious answer is that WPF offers a richer user experience than WinForms, allowing for animations (even 3D) in the user interface, for example.

From a development perspective, it goes a long way to enforce the separation of the User Interface (in the XAML) from the business logic (in VB.NET or C#), which is always a good thing.

A Google search for "WPF vs WinForms" brings up lots of pages that discuss this issue. I won’t repeat all their findings here, but this page raises some interesting points:

  1. Databinding in WPF is superior to what Windows Forms offers.
  2. UI and C# business logic can be cleanly separated in WPF
  3. Storyboard
  4. Data/control templates – a much cleaner way than anything Windows Forms can offer.
  5. Styles – cool and simple. Its so easy to style all your buttons in an application to have the same look and feel.
  6. Even if the VS designer breaks, its easy to code XAML.
  7. UI virtualization – I’ve got grids with 100K rows, ticking off a moving market. Performance would be dreadful if it wasn’t for UI visualization which come for free.
  8. 3D support.
  9. Nothing scientific but, UI development feels quicker in WPF – maybe its just because a WPF application looks cooler at the end of an iteration, or maybe its because development really is quicker.
  10. I can add a User Experience engineer to my team, and with no C# knowledge he can work magic in Expression Blend and give the front-office trading application a makeover that is guaranteed to win over the business users.

ChrisF's user avatar

WPF is the current platform for developing Windows desktop applications. It is a modern, advanced, hardware accelerated framework for developing applications that maintain separation of concerns. It supports advanced rendering of 2D vector and 3D graphics, providing an immense range of capabilities for building rich, interactive, and quality user interfaces.

WinForms, on the other hand, provides a basic platform for developing "classic" Windows apps with your standard look and feel using standard controls. It does not offer the rich, hardware accelerated, vector 2D and 3D capabilities that WPF offers. WinForms applications tend to have much greater coupling between application behavior and UI (view), which presents a less flexible platform upon which to develop applications.

As for which one you choose, it entirely depends on your needs. If you need vector graphics, 3D rendering, the ability to create rich, interactive, animated, modern user interfaces, and/or wish to maintain separation of concerns, WPF is definitely the right choice. If you need none of that, and just need to create a simple UI that solves a simple problem, WinForms will meet your needs just fine.

WPF vs Winforms. Which should you choose ?

Ezoic

report this ad

Ezoic

report this ad

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

Ezoic

report this ad Categories

Microsoft has two main technologies to build native desktop applications, WPF and Winforms. If you are looking to pick a framework it is important that you have a good understanding of the features of each framework.

Winforms is a legacy framework to build desktop applications while WPF is the main framework promoted by Microsoft to build desktop applications.

In this article we will uncover the differences between WPF vs Winforms

What is Winforms?

Winforms (Window Forms) is a Graphical UI library by Microsoft in 2002 to build rich client windows based applications as a part of the .NET system. Winforms provides common controls like textbox, buttons, lists, grids, etc. by wrapping WINAPI/Win32 managed code. Window Forms development is very simple as it is based on a drag and drop placement of UI controls on canvas.

Benefits of Winforms

  • Winforms was released in 2002 and has a large community behind it
  • Winforms have a low learning curve as the UI can be built with a visual tool.

Drawbacks of Winforms

  • Winforms is not supported in .net Core.
  • Microsoft recommands WPF if you are building new applications as Winforms was officially deprecated in 2014.

What is WPF?

Windows Presentation Foundation (WPF) is Graphical UI library from Microsoft WPF is built on top of DirectX providing vector-based graphics. It provides diverse media types, recordings, 3D substance, and a lot of built-in animation. WPF provides craftsmanship interactive media enhanced visualizations. Allowing developers the ability to build flashy UI with limited effort.

Here we list main features of WPF.

  • WPF depends on vector-based design, UI components are scalable to any size without distortion or pixelation.
  • WPF can isolate application rationale code from the UI code. Visual Graphic Designer / Architect and Programming Engineer can work independently.
  • WPF is equipped with built-in storyboard and animations.
  • WPF supports 2D,3D graphics, and many Control templates to make UI more flexible.
  • WPF application can likewise be utilized as an Internet application. The application can be embedded in the browser using XBAP/Silver light.

Key Differences Between Winforms and WPF

The following are the main differences between Winforms and WPF

Technology

WPF is a graphical User Interface based on Direct X with XAML Support. Winforms is a graphical User interface providing access to the native windows library of Common Controls.

Designing Methodology

Winforms uses event-driven controls. WPF utilizes markup language for designing the UI allowing the design of complex user interfaces.

Common Look and Feel

In WPF you have a common look and feel. In Winforms there’s is no common look and feel and you have to define a separate style for each object or component.

Data Binding

WPF usedData Binding. Data Binding provides an mechansim for data flow between the business layer and the UI. Change of data in the UI is reflected in the business layer and vice versa. Data binding provides an easy way to for application to interact and update data.

Declarative Programming

WPF utilizes Extensible Application Markup Language(XAML), which is the next level of declarative programming. The blend of WPF and XAML is like utilizing HTML to build a User Interface, however with an unfathomable scope of expressiveness.

Powerful Animation and Graphics

Winforms uses GDI or GDI+ for Graphics while WPF provides access to DirectX easily accommodating 2D,3D graphics, and animation objects.

Resolution Independence and Device-independent graphics

One of the major plus points of WPF over Winforms is Resolution Independency and device- independent Graphics . This means that WPF is not bothered or dependent on Monitor resolution.Because of vector-based innovation, the WPF application will look good on any resolution or device

Winforms are pixel-based, the application will become destorted on different Monitor resolutions.

Separation of Presentation and Logic

The most important discussion regarding the development point of view about WPF vs. Winforms is that WPF has a model where you separate Graphics User Interface logic from application logic. In Winforms, the Presentation layer is tightly bound with behind coding, WPF uses XAML for the presentation layer.

Faster Execution of WPF over Winforms

Winforms always is limited to software rendering technology while WPF can use hardware rendering.

Use cases when to choose Winforms and WPF

Now keeping in mind all the differences between the two frameworks we cover the use cases when you should use Winforms or WPF.

Scenario 1: Web Support

As we have already listed in WPF features, that WPF can run for both a desktop or web-based application, which is not for Winforms.

Hence if we are going to build some applications that we have the intention to use also as web then WPF is the best choice over Winforms.

WPF can be easily accommodated with its exiting look and feel in browers using XBAP (XAML Browser Application) or Silverlight.

Scenario 2: Cross Platform Support

WPF has now been included as part of the .net core framework which means that WPF applications can now run on linux and on mac os.

Читать:
Как посчитать средний балл оценок в excel

Conclusion

WPF has a lot of advantages over Winforms like Better GUI, Animation, 2D and 3D graphic support, Web application support, and faster acceleration and cross plagorm support.

If you are building a new application you should opt for WPF as it is the main development platform for native window applications. WinForm was officially depreacted by Microsoft in 2014. Use Winforms only if you still need to maintain legacy Winforms applications that cannot be ported to WPF

Let the battle begin: WinForms vs. WPF

When it comes to Windows development, the one question usually appears — WPF or WinForms? Usually experienced developers, as well as newbies, are in doubts: if they know WinForms well enough, do they actually have to improve knowledge in WPF? What for? In this article we’d like to describe main pros and cons of each technology. Let’s move forward to clear awareness and understanding!
Probably, the most popular delusion about these two technologies is that WPF was created to replace WinForms. But, actually, WPF is not intended to replace Windows Forms. WinForms is still alive! Also, Microsoft is going to support WinForms. The technology is still popular among developers — it’s needed and irreplaceable. So, let’s begin our modest investigation with WinForms. Let’s find out why do we need it and in what cases this technology can be really useful.

WinForms
WinForms is a platform for Microsoft Windows application development. Actually, it’s a graphical class library which provides a minimal functionality of a user interface element. It works with color, size, text and font, location, etc. Also, it can be applied for some actions like click and drag/drop. This platform is great for client applications development for desktop, laptop, and tablet PCs. In general, WinForms is simply a layer on a top of standard Windows controls. Applications made with this technology are usually used in development of desktop applications, when a programmer wants the entire processing burden to be rested on the client’s machine. Such approach comes from graphics applications drawing for data-entry and point-of-sale systems. In this case it’s really important to understand that designing your unique interface in WinForms requires a lot of work needed to be done. Also, you should pay an extra cost to buy third party controls. Actually, this is the moment when WPF comes out on top.

WPF
So, what is meant with the acronym WPF? It stands for Windows Presentation Foundation — a system for building Windows client applications. It was created by Microsoft to use it for rendering user interfaces in Windows-based applications. That’s why one of the purposes of WPF is to implement the functionality which responds to user interactions such as clicking on a menu or moving through the tool bar. WPF includes a vector-based and resolution-independent rendering engine. And that is the reason why WPF can build user interfaces with common media elements — vector and raster images, audios, videos, etc. Also, it’s important to understand that WPF is an approach to a GUI framework. And you may know that GUI framework creates thousands of opportunities for a developer who wants to create an application with labels, textboxes and other GUI elements.

What is the difference
So, if everything is so obvious and understandable, what technology should you use? Let’s talk about milestones of these systems. All the points are extracted from a feedback given by experienced developers. If to compare WinForms and WPF, one of the most important differences is that while WinForms is just a layer on top of the standard Windows controls, WPF doesn’t rely on standard Windows controls in almost all situations. In a result, it has a huge impact on a systems’ flexibility — WPF is definitely a flexible one! But you have to pay for everything. That’s why this flexibility has an obvious drawback — you’ll have to work harder to achieve those things which could be done easily with WinForms. Among other WPF’s advantages are ability to make rich and interactive UIs, inherent scalability, powerfull styling and skinning structure, ability to reuse existing code, as well as highly advanced databinding possible.

Obviously, there are some cons of Windows Presentation Foundation, where WinForms comes out on top. Mostly, it’s about WPF’s in-box control suite. Actually, it’s more limited than that one in WinForms. Also, WPF can’t run on Windows 2000 or lower. And when it comes to examples, it’s not easy to find some for the WPF. And in this case it’s time to come the advantages of WinForms. One of them is a plenty of examples. WinForms is widely used among developers, and it’s much older than WPF. Actually, it even supports WPF — huge advantage for those who’re on a way of learning WPF and already feel free with WinForms.
As you may see, there are a lot of pros and cons of WPF, as well as WinForms. But somehow each of them has it’s own fans. Anyway, the chose is up to your experience and expectations. But don’t forget to share with us your experiences. We’ll really appreciate it!

WPF vs. WinForms

В предыдущем разделе мы определили, что такое WPF и начали обсуждение более старого фреймворка — WinForms. В этом разделе я постараюсь сравнить данные модели, так как, несмотря на одинаковое предназначение, между ними существует множество различий. Если Вы никогда не работали до этого с WinForms и, особенно, если WPF это Ваш первый в изучении GUI фреймворк — можете пропустить текущий раздел, но если все же интересно, прочитайте ниже про различия между WPF и WinForms.

Одним из самых важных различий между WinForms и WPF является тот факт, что в WinForms интерфейс пользователя это всего лишь графический слой, использующий стандартные элементы управления Windows (например TextBox), а WPF-интерфейс, в свою очередь, построен «с чистого листа», не опираясь в большинстве случаев на стандартные элементы. Это может показаться весьма тонкой гранью между рассматриваемыми моделями, но в действительности это не так, и Вы обязательно обратите на это внимание при работе с фреймворком, базирующимся на Win32/WinAPI.

В качестве примера вышеописанной ситуации можно рассмотреть кнопку с изображением и текстом на ней. Этот элемент управления не является стандартом Windows, и, в таком случае, WinForms не предоставляет готового решения. В результате Вы будете вынуждены создать изображение и заимплементировать собственную кнопку, поддерживающую изображения либо воспользоваться готовыми нестандартными решениями. Кнопка в WPF, в свою очередь, может иметь внутри что угодно, так как это просто «рамка», содержащая графический контент, находящаяся в разных состояниях (например: нажатая, ненажатая, реагирующая на наведенный курсор). Ее можно трактовать как «невидимую» (это относится к большинству других элементов управления WPF), это значит, что она может содержать в себе ряд других элементов внутри. Вы хотите получить кнопку с изображением и текстом? Просто поместите элементы Image и TextBlock внутрь кнопки и она готова! В рамках элементов управления WinForms Вы просто не ощутите той гибкости при разработке, что является причиной процветания рынка, который предлагает готовые простые реализации таких элементов как «кнопка с изображением» и подобных.

Слабой стороной гибкости, о которой шла речь является то, что Вам придется больше работать для достижения результата, который просто можно было бы достичь в WinForms, так как она была создана для определенных сценариев. Как минимум, это будет ощутимо в начале, когда Вы захотите например создать шаблон ListView с изображением и хорошо выровненным текстом, тогда как ListView в WinForms это всего лишь одна строка кода.

Выше было представлено лишь одно из различий, но когда Вы начнете работать с WPF, то поймете, что оно является причиной большого количества других — просто WPF устроен по своему, хорошо это или плохо — решать Вам. Больше никаких ограничений элементами управления платформы Windows, но для того, что достичь гибкости, о которой шла речь — придется приложить больше усилий, по сравнению с созданием стандартных Windows интерфейсой пользователя.

Ниже приведено полностью субъективное мнение на тему ключевых преимуществ WPF и WinForms. Это может помочь вам понять, какую из технологий стоит использовать.

Похожие статьи