Что лучше wpf или windows forms

По поводу устарелого дизайна, я вас не понял…

По поводу поддержки Win Forms мне кажется она никуда не делась, в этом можно убедиться почитав новости про Visual Studio 2017 и .net 4.7.

Лично мои наблюдения:

WPF говорит от потрясающем быстродействии в отрисовке элементов на экране благодаря работе на DirectX. У меня комп прекрасен всем — и CPU и GPU, но, по факту, отрисовка на экране у Win Forms гораздо быстрее (GDI тоже на месте не стоит).

Контрол DataGrid на WPF крайне сырой(по крайней мере пару лет назад был).
Это самый важный контрол для представления данных вообще. Он должен быть очень универсальным, именно такой он в Win Forms, но не в WPF.
Для виртуализации данных в DataGrid (WPF) можно использовать только виртуализацию самого источника данных через DataSource.

В Win Forms с DataGridView можно делать буквально все, что только угодно благодаря старому доброму механизму событий(CellVlueNeeded и CellValueFormating), причем очень просто (ну и DataSource тоже на месте).

Кстати, может кто то подскажет, появился способ в DataGrid поставить програмно фокус в строку номер N не прибегая к коду в 30 строк с применением рефлексии?

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

Для бизнес-приложений важно как раз все остальное, эти приложения люди используют долгое время, по многу часов в день. Функционал их сложен и, как правило, нестандартен. Поэтому их интерфейс должен быть максимально функциональным и не оттягивать внимание на самого себя. Человек не должен уставать от пестрого и мультяшного интерфейса.

В пользу WPF скажу только, что сам принцип построения интерфейса в нем очень интересен тем, что похож на таковой в интернет-страницах. Это очень интересно, но пока сыро (до сих пор! Когда был впервые представлен WPF!?)…
И да, я не обожаю XAML.

-;)

1 — если смотреть в будущее (вин10) и метить на витрину магазина МС — еще лучше сразу UWP

2 — но мордочки для винформ тоже есть:
— https://github.com/Wagnerp/Krypton-NET-4.7
— https://github.com/N-a-r-w-i-n/MetroSet-UI

3 — если метить на трудоустройство в корпоративный сектор — все популярные библиотеки компонентов .net, типа DevExpress, Telerik, Syncfusion и тд — дают триалы, не грех поиграть (там и формы, и впф и увп, и веб..)

отдельно про Syncfusion — у них есть хитрая лицензия для практически не ограниченного бесплатного использования, даже коммерческого в каких то пределах (но подробности уже у них на сайте ищите)

ps

если чисто для десктопа — формы+мордочки проще и мало в чем уступают, а работа с треем по дефолту доступна именно в формах

минус и форм и впф — встроенный браузер — это IE (тут отвечал подробно — придется осваивать или CEF# или GeckoFX, новичку это будет сложно)

… а в UWP — уже Edge, там все гораздо веселее

так что нюансы свои есть везде, стоит пробовать все, а по мере понимания уже выбирать платформу исходя из особенностей задачи

pps

вот статья от крутого эксперта, первые два пункта как раз вам по теме почитать.. статья ооочень старая, но суть далеко не все «гуру» знают даже сегодня ;))

If you’re a developer trying to choose between WPF and WinForms, you’re probably wondering about the differences between these two technologies. In this guide, we’ll provide an in-depth comparison of WPF and WinForms, outlining the key differences and similarities between them.

A Brief Overview of WPF and WinForms

Windows Presentation Foundation (WPF) is a UI framework for building desktop applications, introduced by Microsoft in 2006. WPF was created to replace WinForms, which had been the primary UI framework for Windows desktop applications since 2002. While WinForms is still in use today, WPF provides a more modern, visually appealing UI framework built on top of DirectX.

WinForms, on the other hand, is a UI framework that uses the Windows API to create desktop applications in Windows. It is the traditional UI framework for Windows desktop applications, and it is still widely used today.

One of the key differences between WPF and WinForms is the way they handle graphics. WPF uses a vector-based graphics system, which allows for high-quality, scalable graphics that can be easily animated and manipulated.

WinForms, on the other hand, uses a raster-based graphics system, which can result in lower-quality graphics and limited animation capabilities.

Another difference between the two frameworks is their support for modern UI design principles. WPF includes support for features like data binding, styles, and templates, which make it easier to create consistent, modern-looking UIs.

WinForms, on the other hand, is more limited in its support for these features, which can make it more difficult to create modern UIs without resorting to custom code.

Understanding the Fundamental Differences between WPF and WinForms

The key difference between WPF and WinForms is the underlying technology. WPF uses DirectX for rendering, while WinForms uses the Windows API.

This means that WPF can take advantage of the hardware acceleration provided by DirectX, resulting in more visually appealing and responsive UIs. WinForms, on the other hand, is limited by the capabilities of the Windows API.

Another difference between WPF and WinForms is in their approach to UI layout. WPF uses a more modern approach to layout that is based on XAML, while WinForms uses a more traditional approach that is based on forms and controls.

This means that WPF provides more flexibility and control over the layout and appearance of the UI, while WinForms is simpler to use for basic UI design.

One more difference between WPF and WinForms is in their support for multimedia content. WPF has built-in support for multimedia content such as audio, video, and animation, while WinForms requires additional libraries or plugins to support multimedia content.

This makes WPF a better choice for applications that require multimedia content, such as video players or interactive presentations.

User Interface Design in WPF vs WinForms: Which Offers More Flexibility?

When it comes to user interface design, WPF is widely considered to be the superior technology. WPF provides a rich set of controls and features for designing visually appealing UIs, including support for advanced graphics and animation.

Additionally, WPF supports a more modern approach to UI design, allowing for more flexibility and control over the layout and appearance of the UI.

WinForms, on the other hand, is simpler to use and more straightforward for basic UI design. It offers a range of standard controls that allow developers to create basic UIs quickly and easily. However, for more advanced UI design, WinForms can be limited and inflexible.

One of the key advantages of WPF over WinForms is its ability to support vector graphics. This means that UI elements can be scaled up or down without losing quality, making it ideal for high-resolution displays. Additionally, WPF allows for the creation of custom controls, which can be reused across multiple projects, saving time and effort for developers.

Another advantage of WPF is its support for data binding, which allows UI elements to be automatically updated when underlying data changes. This can be particularly useful for creating dynamic UIs that respond to user input or changes in data.

WinForms also supports data binding, but it is not as flexible or powerful as WPF’s implementation.

Performance and Scalability: A Comparison of WPF and WinForms

When it comes to performance and scalability, there are some differences between WPF and WinForms. WPF’s use of hardware acceleration means that it can provide more visually appealing and responsive UIs.

However, this can come at a cost in terms of performance, particularly for complex UIs. Additionally, WPF can be resource-intensive, which can impact performance on lower-end systems.

WinForms, on the other hand, is generally considered to be a more lightweight and performant UI framework. While it may not provide the same level of visual appeal as WPF, it can provide responsive UIs even on lower-end systems.

Another factor to consider when comparing WPF and WinForms is their compatibility with different operating systems. WPF is primarily designed for Windows operating systems, which limits its cross-platform capabilities.

On the other hand, WinForms, while also primarily designed for Windows, can be used on multiple platforms, including Windows, Linux, and macOS, through the use of third-party libraries like Mono, making it a more versatile option for developers who need to create applications for different operating systems.

Compatibility with Modern Technologies: How WPF and WinForms Stack Up

When it comes to compatibility with modern technologies, both WPF and WinForms have their strengths and weaknesses.

WPF is generally considered to be more modern and future-proof, with support for features like touch and high DPI displays. However, it can be more challenging to integrate with legacy systems, particularly those built on WinForms.

WinForms, on the other hand, has been around for longer and has a more established ecosystem.

This means that it can be easier to integrate with legacy systems, as well as to find resources and support for development. However, WinForms lacks some of the advanced features supported by WPF, which can limit its compatibility with modern technologies.

Development Environment: Which is Easier to Use, WPF or WinForms?

When it comes to ease of use, both WPF and WinForms have their strengths and weaknesses. WPF provides a more modern and intuitive development experience, particularly for UI design. However, since WPF is a newer technology, it can take some time to learn and become proficient in.

WinForms, on the other hand, is more straightforward and easier to use for basic UI design. Additionally, since it has been around for longer, there are more resources and support available for WinForms development. However, WinForms can be more limiting and less flexible than WPF, particularly in terms of UI design.

Choosing the Right Technology for Your Project: Factors to Consider

When choosing between WPF and WinForms for your project, there are several factors to consider. These include:

  • The complexity of your application
  • Your UI design requirements
  • The performance requirements of your application
  • Your target platform and compatibility requirements
  • Your development experience and expertise

By carefully considering these factors, you can make an informed decision about which technology is best suited for your project.

Pros and Cons of Using WPF versus WinForms

To help summarize the key differences between WPF and WinForms, here are some of the pros and cons of each technology:

WPF:

  • Pros:
  • Cons:

WinForms:

  • Pros:
  • Cons:

Case Studies: Real-World Examples of Applications Built with WPF and WinForms

To help illustrate the key differences between WPF and WinForms, here are some real-world examples of applications built with each technology:

  • ArcGIS Pro: An example of a complex GIS application built with WPF, leveraging its advanced graphics and animation support.
  • Paint.NET: An example of a lightweight image editing application built with WinForms, highlighting its simplicity and ease of use.

By considering these examples and the factors outlined above, you can make an informed decision about whether WPF or WinForms is best suited for your project.

Штейников Р.С. 1


1Волжский политехнический институт (филиал) ФГБОУ ВПО «Волгоградский государственный технический университет»


Текст работы размещён без изображений и формул.
Полная версия работы доступна во вкладке «Файлы работы» в формате PDF

Введение

Windows Forms – графическая система в составе .Net Framework. Представляет собой обертку вокруг Win32 API в управляемом коде. Считается заменой графической системы MFC, написанной под C++ и имеет сложную модель для разработки интерфейса программного продукта.

Windows Presentation Foundation – это графическая система в составе .Net Framework 3.0 и более поздних версий. Спроектирована под влиянием технологий HTML и Flash и использует аппаратное ускорение.

Изменения графических систем отображения Windows

Разработка графического интерфейса для Windows-приложений основывается на двух компонентах операционной системы:

  1. User32 – содержит основные элементы окна;

  2. GDI/GDI+ — предоставляет функционал для рисования фигур, текста.

Эволюция графических систем прошла путь от сложной системы MFC до разработки на языках .Net и WinForms. Но как бы не совершенствовались технологии разработки, они всё равно опирались на User32 и GDI/GDI+, а значит, не смогли преодолеть фундаментальные ограничения базовых компонентов.

Для решения этой проблемы была разработана технология WPF. Её главное отличие от WinForms в том, что для отображения графических компонентов используется не GDI/GDI+, а DirectX – технология, разрабатываемая Microsoft для создания игр в тесном сотрудничестве с изготовителями видеокарт, и по этой причине имеет поддержку аппаратного ускорения.

И хоть от компонента User32 не отказались, его использование сводится к задачам не касающихся отображения графического интерфейса, например, определение положения окна. Все задачи, связанные с рисованием возложены на DirectX.

Преимущества WPF

Переход к DirectX представляет собой огромный шаг в развитии и, априори, предоставляет такое превосходство перед другими графическими система как аппаратное ускорение. Однако, WPF обладает и рядом других преимуществ, которые так же повышают его привлекательность для разработчиков.

Рассмотрим наиболее существенные изменения:

  • Аппаратное ускорение. Как уже было сказано, DirectX разрабатывался в сотрудничестве с изготовителями видеокарт. Однако, просто мощной видеокарты недостаточно, необходима программная поддержка. Именно по этой причине с 2004 года изготовители видеокарт при написании драйверов следуют новым инструкциям от Microsoft.

Аппаратная поддержка предоставляется всем приложениям. В момент запуска анализируются возможности видеокарты и на основание полученных результатов присваивается уровень визуализации от 0 до 2.

Уровни визуализации:

  1. Уровень 0 – отсутствие аппаратной поддержки.

  2. Уровень 1 – частичная аппаратная поддержка.

  3. Уровень 2 – полная аппаратная поддержка.

  • Декларированный пользовательский интерфейс. Еще одно нововведение в WPF это язык разметки XAML, являющийся подмножеством XML. Хотя весь пользовательский интерфейс можно описать на языке C# (или другом языке .Net), технология WPF использует другой подход, следуя которому интерфейс описывается на языке XAML, а поведение программы записывается в коде. Теперь дизайнер и разработчик могут работать параллельно и не вникать в работу друг друга.

  • Стили. В основу идеи отрисовки пользовательского интерфейса легла технология HTML. Переход к разработке на XAML дал возможность выводить свойства элементов окон в отдельные стили, по аналоги с CSS. И теперь изменить внешний вид окон стало ее проще, достаточно просто заменить файл со стилями.

  • Модель рисования. Если в WinForms рисовали пиксели, то в WPF работают с примитивами – это уже готовые базовые фигуры и прочие графические элементы. Кроме того, имеется встроенная поддержка трехмерно графики.

  • Анимация. В WinForm для того, чтобы форма отрисовала себя, необходимо использовать таймеры. При разработке технологии WPF в Microsoft пошли другим путем и дали ей поддержку анимации.

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

  • Команды. Также, как и в WinForms, в WPF присутствует событийная модель, базовые элементы были переписаны и наделены новыми возможностями, что также отразилось на событиях, и, тем не менее, принцип остался прежним. Иногда разные компоненты окна вызывают одно и тоже действие, но которое вызывается в разных обработчиках событий. В WPF появился способ вызвать реакцию элемента интерфейса через так называемые команды. Команды подчиняются определенным правилам, например, название метода оканчивается на Command, которое опускается при вызове метода.

  • Приложения на основе страниц. Можно строить веб-подобные приложения на основе страниц, что дает возможность пользоваться навигацией.

  • Безопасность. Ранее при разработке приложения, в него могли записать опасный код. Повышение уровня открытости и безопасности стали одними из причин появления языка XAML.

  • Независимость от разрешения. WPF берет на себя компоновку элементов интерфейса подстраивая его под разные разрешения.

  • Привязка данных. Привязать данные можно было и в WinForms, но в WPF этот механизм доведен до совершенства. Благодаря привязке существенно снижается количество строк кода и упрощает его анализ.

Заключение

Исходя из стратегии развития Microsoft, можно предположить, что технология WPF будет развиваться и дальше. Например, эта технология используется для написания приложений в стиле Metro.

Если сравнивать графические системы WinForms и WPF, то можно прийти к выводу, что вторая система имеет огромное превосходство. Единственным существенным достоинством WinForms можно назвать кроссплатформенность, такие приложения можно запустить на Mono. О планах по поддержке WPF в системах семейства Unix нет никаких сведений.

Но это не значит, что стоит забыть о технологии WinForms и все свои проекты переводить на WPF. Microsoft не сообщала о прекращение поддержки WinForms. Кроме того, у нее имеется большая история развития, а, следовательно, под неё написано множество готовых решений. Проекты, в которых пользовательский интерфейс стоит не на первом месте, могут быть написаны и на WinForms.

Библиографический список

  1. МакДональд, Мэтью. WPF 4: Windows Presentation Foundation в .Net 4.0 с примерами на C# 2010 для профессионалов. : Пер. с англ. – М. : ООО «И.Д. Вильямс», 2011. – 1024 с. : ил. – Парал. тит. англ.

  2. Электронный ресурс http://vbibl.ru/informatika/119332/index.html

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. 

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

  • Что лучше ubuntu или windows 11
  • Что лучше планшет на android или windows
  • Что значит чужой диск в windows 10
  • Что значит система не обнаружила vcruntime140 dll для windows 10
  • Что лучше windows или mac os или linux