.NET MAUI Triggers

Triggers in .NET MAUI are not that different from triggers in Xamarin.Forms, but since this is not a frequently used feature, I thought I’d provide a quick deep-dive into their usage.

Triggers allow you to declare, in your XAML, how a control should appear based on data changes. You can combine state triggers with Visual State, a topic I’ll cover in a subsequent blog post.

This is the first of a series of short pieces based on material in my forthcoming book .NET MAUI For C# Developers (Packt* Publishing) which we are targeting for publication in early April.

For example, suppose we have a create account page, and we want the create button to be disabled if the user has not filled in a password. You can certainly do this in code (and .NET MAUI Community Toolkit will make this very easy with behaviors), but you can also do it declaratively in XAML using a DataTrigger.

<Button
    Command="{Binding DoCreateAccountCommand}"
    Grid.Column="1"
    Grid.Row="2"
    Style="{StaticResource LoginButton}"
    Text="Create Account">
    <Button.Triggers>  
        <DataTrigger
            Binding="{Binding Source={x:Reference passwordEntry}, Path=Text.Length}"
            TargetType="Button"
            Value="0"> 
            <Setter Property="IsEnabled" Value="False" /> 
        </DataTrigger>
    </Button.Triggers>
</Button>

Notice that the Button has a collection of Triggers. The type we want is a DataTrigger (as opposed, for example, to an event trigger). The trigger binds to the passwordEntry field’s Text.Length and looks for the value 0. If that is true, then the property IsEnabled is set to false. Once the Text.Length is not zero, the property is set to true.

That’s all it takes. You can see that triggers are often quite simple, but for some reason considered “advanced” and thus not used often; which is a shame because they can greatly simplify your code and make the logic easier to understand.

Note that the field you are checking (in this case password) must have its Text initialized to “” (in the ViewModel or code-behind, but of course the ViewModel is the right place). Otherwise it will be null, and the trigger may not act as expected.

In my next tutorial, I’ll tackle the more interesting and complex subject of Visual States.

———–

*This being my second book from Packt, I decided to ask how it is pronounced. Turns out it is one syllable, sounding more like packed than like packet. If you want to get it really right, say the word pack and sneak in a t sound at the end. (Just thought you’d want to know.)

Unknown's avatar

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. Liberty is a Senior AI Engineer at the University of Pittsburgh Medical Center, and was a Team Lead and Senior Software Engineer for various corporations, a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a 21 year Microsoft MVP.
This entry was posted in Essentials. Bookmark the permalink.

4,198 Responses to .NET MAUI Triggers

  1. Web's avatar Web says:

    Informative and engaging — nice!

  2. Web's avatar Web says:

    Very smooth and engaging read.

  3. Web's avatar Web says:

    Truly thoughtful writing!

  4. Web's avatar Web says:

    Truly enjoyed this content!

  5. Web's avatar Web says:

    Great job — loved it!

  6. Web's avatar Web says:

    You made this topic exciting!

  7. Web's avatar Web says:

    You’re a talented writer!

  8. Web's avatar Web says:

    This post adds real value!

  9. Web's avatar Web says:

    Very well researched content!

  10. Web's avatar Web says:

    Really enjoyed this piece.

  11. Web's avatar Web says:

    Such a thoughtful article.

  12. I never knew .NET MAUI triggers could be so powerful, almost like a secret switch behind the scenes! It reminds me of designing an exhibition stand pop-up—one tiny detail changes, and suddenly everything transforms. I wonder if my code could ever pop with the same surprise as a well-lit trade show booth!

  13. Попробуйте удачу в Lucky Pari рабочее зеркало и получайте незабываемые эмоции!
    Клиентская поддержка работает круглосуточно и готова помощь.

  14. Web's avatar Web says:

    Clear message, great execution.

  15. Web's avatar Web says:

    Clear, sharp, and inspiring.

  16. Web's avatar Web says:

    I admire your writing skills!

  17. Web's avatar Web says:

    Keep writing — this is great!

  18. Web's avatar Web says:

    Loved the flow of this article.

  19. Web's avatar Web says:

    You have a gift for explaining things.

  20. Web's avatar Web says:

    You explained everything so well.

  21. Web's avatar Web says:

    Such a well-crafted post!

  22. Web's avatar Web says:

    Excellent writing — keep it up!

  23. Web's avatar Web says:

    This was a great read!

  24. Web's avatar Web says:

    I learned a lot from this!

  25. Web's avatar Web says:

    Your writing style is amazing!

  26. Web's avatar Web says:

    A solid, well-written piece.

  27. Web's avatar Web says:

    So much value in one post!

  28. Web's avatar Web says:

    Every sentence adds value.

  29. 1win_rrMr's avatar 1win_rrMr says:

    Погрузитесь в захватывающий мир авиатор 1 win и испытайте удачу!
    Игра предлагает напряжённый игровой процесс, который удерживает внимание участников.

  30. Наслаждайтесь увлекательными играми и щедрыми бонусами в LuckyPari!
    Платформа LuckyPari известна своей уникальностью, которая предоставляет пользователям широкий спектр услуг. В LuckyPari доступно огромное количество спортивных событий, на которые можно делать ставки. Все это способствует повышению лояльности клиентов. которые могут столкнуться с различными вопросами. Такой подход к обслуживанию клиентов значительно увеличивает уровень их удовлетворенности.

  31. Josephmok's avatar Josephmok says:

    Осознанный подход к игре является ключевым элементом комфортного развлечения.
    Она помогает избежать лишних рисков и сохранять баланс во время развлечений.
    Множество пользователей понимают, что взвешенное поведение помогает наслаждаться игрой без дискомфорта.
    Умение ставить лимиты позволяет регулировать активность.
    https://blokov-casino.net/online-casino-flagman/
    Помимо этого, важно следить за эмоциями и устраивать перерывы.
    Сервисы часто предлагают инструменты самоконтроля, которые помогают играть безопасно.
    Игроки, которые придерживаются принципов ответственности, чаще поддерживают эмоциональный комфорт.
    Следовательно, ответственная игра остаётся необходимым условием комфортного отдыха.

  32. WilliamAdone's avatar WilliamAdone says:

    In clinical practice, one often observes the unidirectional flow of medical instruction. A treatment plan is formulated and executed — this dynamic has been a cornerstone of modern medicine. This model, while efficient, overlooks critical variables.
    The clinical picture, however, is frequently complicated by comorbidities. One begins to note a prevalence of treatment-resistant cases. These can range from persistent subclinical fatigue to cognitive disturbances. An analysis of individual metabolic and genetic factors often reveals a landscape of interactions that was not initially apparent.
    This is the cornerstone of personalized medicine. The same molecular entity can be curative for one patient and merely palliative or even detrimental for another. Long-term health outcomes are shaped by these subtle, cumulative decisions.
    Therefore, fostering a collaborative doctor-patient relationship is paramount. The informed patient is empowered to work synergistically with their healthcare provider. For those seeking to deepen their understanding of this complex interplay, we advise delving into the subject further. A prudent starting point for any individual would be to research and better understand silagra 100 mg.
    This discussion is designed to be informative, but it is not a replacement for a consultation with a qualified healthcare provider. Always seek the advice of your physician or another qualified health professional with any questions you may have regarding a medical condition.

  33. Wallybland's avatar Wallybland says:

    Регулярное выполнение домашней работы играет важную роль в учебном процессе.
    Это занятие помогает повторять изученные темы и повышать успеваемость.
    Юные учащиеся осознают, что домашняя работа способствуют развитию дисциплины.
    Регулярная практика позволяет развить логическое мышление.
    https://kolyma.ru/allpubnews/138445-vrednaya-shpargalka-tak-li-opasny-sborniki-gotovyh-domashnih-zadaniy.html
    Педагоги нередко подчеркивают, что домашняя подготовка помогает глубже понимать темы.
    Кроме того, домашняя работа приучает к ответственности.
    Учащиеся, которые выполняют задания, обычно проявляют больше уверенности.
    Таким образом, выполнение домашних заданий остаётся важным элементом обучения для каждого школьника.

  34. Mike Janecek's avatar Mike Janecek says:

    Ik speel af en toe bij het download kokobet apk voor Android wanneer ik gewoon even wil ontspannen. De site laadt snel, je hoeft niets te downloaden en alles werkt soepel. Er is een ruime keuze aan spellen en de uitbetalingen zijn echt snel – precies wat je nodig hebt als je na een lange dag gewoon een paar spins wilt doen.

  35. Ik speel af en toe bij het learn about koko bet reward system wanneer ik gewoon even wil ontspannen. De site laadt snel, je hoeft niets te downloaden en alles werkt soepel. Er is een ruime keuze aan spellen en de uitbetalingen zijn echt snel – precies wat je nodig hebt als je na een lange dag gewoon een paar spins wilt doen.

  36. Miguelon's avatar Miguelon says:

    This is a great technical breakdown. For those who are less technical and just want a simple, working solution, I’ve found that platforms like

    https://wplaydescargar.co/

    are the easiest to get started with. Sometimes simplicity is the most important feature.

  37. Davidendom's avatar Davidendom says:

    Trò chơi có kiểm soát là vô cùng quan trọng để giữ gìn sự cân bằng tâm lý.
    Hành động này hỗ trợ người chơi kiểm soát thời gian chơi một cách hiệu quả.
    Chơi có trách nhiệm giảm thiểu các rủi ro liên quan đến cờ bạc trực tuyến.
    Người tham gia nên đặt giới hạn về nguồn lực và đảm bảo kỷ luật bản thân.
    Skin Club
    Các hệ thống i-gaming hỗ trợ công cụ giới hạn để giúp người chơi trong quá trình chơi.
    Hành động có trách nhiệm giữ gìn trò chơi công bằng.
    Do đó, chơi game có trách nhiệm là vấn đề quan trọng để tận hưởng trò chơi.

  38. Davidendom's avatar Davidendom says:

    La pratique responsable du jeu est important pour tous les joueurs.
    Cette approche permet de profiter des jeux tout en éviter les excès.
    Utiliser des stratégies de jeu responsables aide à éviter les conséquences négatives.
    Les services de jeux en ligne doivent fournir des outils pour faciliter le contrôle personnel.
    CSGO Roll
    La sensibilisation sur le jeu responsable aide les utilisateurs de mieux gérer leur temps.
    Il est nécessaire de suivre ses habitudes afin de éviter les problèmes financiers.
    Les participants prudents profitent davantage de l’expérience.
    Par conséquent, le jeu responsable est un élément clé pour une activité sécurisée.

  39. Philiptob's avatar Philiptob says:

    Современная система очистки играет ключевую роль в бытовых условиях.
    Такая система помогает устранять загрязнения из воды.
    При качественной фильтрации, тем безопаснее становится жидкость для потребления.
    Многие семьи оценивают необходимость использования надёжных очистительных систем.
    Современные технологии позволяют добиться стабильного результата.
    https://progorod62.ru/reyting-filtrov-dlya-vody-pod-moyku-top-7-luchshih-modeley
    Правильно выбранная система помогает защитить здоровье для всей семьи.
    Своевременное обслуживание повышает эффективность водоочистной системы.
    Таким образом, качественная система очистки воды — это основа для безопасного быта.

  40. MalcolmGrida's avatar MalcolmGrida says:

    Оперативная проверка здоровья играет решающую роль в лечебной практике.
    Такая диагностика позволяет обнаружить заболевание на первых шагах развития.
    Когда своевременно проведено обследование, тем эффективнее подобрать лечение.
    Многие пациенты недооценивают роль профилактики, хотя это важный шаг к благополучию.
    https://zdraviie.ru/novosti/prp-terapiya
    Диагностические технологии помогают получить точные данные о состоянии организма.
    Плановые проверки позволяют своевременно реагировать.
    Для врачей раннее выявление болезни — это шанс улучшить прогноз.
    Следовательно, своевременная диагностика является важным элементом заботы о здоровье.

  41. Arisha27sr's avatar Arisha27sr says:

    Hello guys
    Hello. A 27 fantastic website 1 that I found on the Internet.
    Check out this website. There’s a great article there. https://urbanpost.it/dai-giochi-della-tradizione-al-blackjack/|

    There is sure to be a lot of useful and interesting information for you here.
    You’ll find everything you need and more. Feel free to follow the link below.

  42. Arisha27sr's avatar Arisha27sr says:

    Hello comrades
    Good evening. A 27 nice site 1 that I found on the Internet.
    Check out this site. There’s a great article there. https://sehiresnafi.com/which-is-the-best-mobile-sports-betting-app/|

    There is sure to be a lot of useful and interesting information for you here.
    You’ll find everything you need and more. Feel free to follow the link below.

  43. Thomasver's avatar Thomasver says:

    Сегодняшние средства массовой информации играют значимую роль в общественной жизни.
    Эти ресурсы помогают людям быстро находить актуальные сведения.
    С помощью медиа общество остается в курсе событий.
    СМИ всех форматов формируют общественное мнение.
    Важно учитывать, что качество информации напрямую определяет мнение аудитории.
    Большинство пользователей выбирают те источники, которые обеспечивают проверенные материалы.
    Медиа также позволяют поддерживать диалог между различными группами населения.
    Таким образом, СМИ остаются неотъемлемой частью современного общества.
    http://forum.drustvogil-galad.si/index.php/topic,235153.new.html#new

  44. скачать Windows Loader's avatar скачать Windows Loader says:

    Triggers in .NET MAUI are such a powerful way to make UI reactive without heavy code-behind. I’m exploring how they can simplify dynamic styling and behavior in my apps. windows10активатор

  45. Charlesspape's avatar Charlesspape says:

    Casino Roulette: Spin for the Ultimate Thrill
    Experience the timeless excitement of Casino Roulette, where every spin brings a chance to win big and feel the rush of luck. Try your hand at the wheel today at https://k8o.jp/ !

  46. Thanks for sharing. I read many of your blog posts, cool, your blog is very good.

Comments are closed.