.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.)

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. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was 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 Microsoft MVP.
This entry was posted in Essentials. Bookmark the permalink.

94 Responses to .NET MAUI Triggers

  1. DanielPiove says:

    Трендовые фасоны сезона 2025 года задают новые стандарты.
    Популярны пышные модели до колен из полупрозрачных тканей.
    Блестящие ткани создают эффект жидкого металла.
    Греческий стиль с драпировкой становятся хитами сезона.
    Минималистичные силуэты подчеркивают элегантность.
    Ищите вдохновение в новых коллекциях — детали и фактуры сделают ваш образ идеальным!
    http://www.sazkar.info/topic-t206406.html

  2. DanielPiove says:

    Модные образы для торжеств нынешнего года отличаются разнообразием.
    Актуальны кружевные рукава и корсеты из полупрозрачных тканей.
    Детали из люрекса делают платье запоминающимся.
    Многослойные юбки возвращаются в моду.
    Минималистичные силуэты создают баланс между строгостью и игрой.
    Ищите вдохновение в новых коллекциях — детали и фактуры оставят в памяти гостей!
    http://forum.drustvogil-galad.si/index.php/topic,173020.new.html#new

  3. Ma mère ne fut pas touchéepar mes larmes,コスプレ r18mais elle ne put retenir un cri a la vue de la coiffedéfoncée et de la douillette perdue.

  4. На этом сайте эротические материалы.
    Контент подходит тем, кто старше 18.
    У нас собраны видео и изображения на любой вкус.
    Платформа предлагает четкие фото.
    домашнее порно онлайн бесплатно
    Вход разрешен только для совершеннолетних.
    Наслаждайтесь безопасным просмотром.

  5. free spins says:

    Within this platform, find a wide range internet-based casino sites.
    Searching for well-known titles new slot machines, there’s something for every player.
    The listed platforms are verified to ensure security, so you can play peace of mind.
    casino
    What’s more, the platform unique promotions and deals for new players and loyal customers.
    With easy navigation, locating a preferred platform is quick and effortless, enhancing your experience.
    Stay updated on recent updates by visiting frequently, as fresh options are added regularly.

  6. Ivanvag says:

    Установка камина и дымоходов в Москве под ключ — профессиональное решение для тех, кто ценит уют, тепло и стиль в доме.
    Мы предлагаем полный комплекс услуг: от консультации и проекта до купли, монтажа и настройки камина и дымохода . Наши
    специалисты выполнят все работы качественно и в срок, соблюдая все строительные и пожарные нормы.

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

    Обратившись к нам, вы получите камин «под ключ» :
    – Консультация по выбору модели
    – Доставка и подъем на этаж
    – Монтаж камина и дымохода
    – Пуско-наладочные работы
    – Гарантия на выполненные работы

    Установка каминов с дымоходомУстановка камина летом в Подмосковье

  7. vavada says:

    Here, explore an extensive selection internet-based casino sites.
    Searching for classic games or modern slots, there’s a choice for any taste.
    Every casino included checked thoroughly for safety, so you can play securely.
    play slots
    Additionally, this resource unique promotions along with offers to welcome beginners as well as regulars.
    Due to simple access, locating a preferred platform happens in no time, enhancing your experience.
    Be in the know regarding new entries through regular check-ins, because updated platforms appear consistently.

  8. 1xbet says:

    Within this platform, explore a variety virtual gambling platforms.
    Whether you’re looking for well-known titles new slot machines, you’ll find an option for any taste.
    All featured casinos fully reviewed to ensure security, allowing users to gamble peace of mind.
    play slots
    Additionally, this resource provides special rewards plus incentives targeted at first-timers and loyal customers.
    Thanks to user-friendly browsing, discovering a suitable site is quick and effortless, enhancing your experience.
    Keep informed about the latest additions with frequent visits, because updated platforms come on board often.

  9. 同性恋者 says:

    本网站 提供 多样的 成人材料,满足 不同用户 的 需求。
    无论您喜欢 哪种类型 的 内容,这里都 种类齐全。
    所有 资源 都经过 精心筛选,确保 高质量 的 浏览感受。
    色情照片
    我们支持 多种设备 访问,包括 电脑,随时随地 自由浏览。
    加入我们,探索 绝妙体验 的 私密乐趣。

  10. 偷窥 says:

    本网站 提供 多样的 成人内容,满足 成年访客 的 兴趣。
    无论您喜欢 哪种类型 的 视频,这里都 一应俱全。
    所有 资源 都经过 精心筛选,确保 高质量 的 视觉享受。
    私人视频
    我们支持 多种设备 访问,包括 电脑,随时随地 畅享内容。
    加入我们,探索 绝妙体验 的 私密乐趣。

  11. play slot says:

    This website, you can discover lots of online slots from leading developers.
    Users can try out retro-style games as well as modern video slots with high-quality visuals and bonus rounds.
    If you’re just starting out or a seasoned gamer, there’s a game that fits your style.
    play bonanza
    All slot machines are ready to play 24/7 and optimized for desktop computers and mobile devices alike.
    No download is required, so you can jump into the action right away.
    Site navigation is user-friendly, making it quick to find your favorite slot.
    Sign up today, and discover the thrill of casino games!

  12. play aviator says:

    On this platform, you can find a great variety of casino slots from top providers.
    Players can experience classic slots as well as new-generation slots with stunning graphics and exciting features.
    Even if you’re new or a casino enthusiast, there’s a game that fits your style.
    slot casino
    The games are instantly accessible 24/7 and optimized for desktop computers and mobile devices alike.
    No download is required, so you can jump into the action right away.
    Site navigation is intuitive, making it quick to browse the collection.
    Join the fun, and discover the world of online slots!

  13. gambling says:

    On this site, explore a variety of online casinos.
    Whether you’re looking for traditional options new slot machines, you’ll find an option for every player.
    The listed platforms are verified to ensure security, enabling gamers to bet with confidence.
    1win
    Additionally, the platform offers exclusive bonuses along with offers for new players and loyal customers.
    Due to simple access, locating a preferred platform is quick and effortless, making it convenient.
    Stay updated on recent updates by visiting frequently, because updated platforms appear consistently.

  14. ErickMox says:

    Mechanical watches stand as the epitome of timeless elegance.
    In a world full of modern gadgets, they undoubtedly hold their sophistication.
    Crafted with precision and mastery, these timepieces showcase true horological excellence.
    Unlike fleeting trends, fine mechanical watches do not go out of fashion.
    https://gravatar.com/arabicbezel
    They represent heritage, tradition, and enduring quality.
    Whether used daily or saved for special occasions, they continuously remain in style.

  15. В данной платформе представлены видеообщение в реальном времени.
    Вы хотите дружеское общение деловые встречи, вы найдете варианты для всех.
    Функция видеочата предназначена для связи людей глобально.
    секс порно чат
    С высококачественным видео и превосходным звуком, каждый разговор кажется естественным.
    Вы можете присоединиться в открытые чаты инициировать приватный разговор, исходя из ваших потребностей.
    Для начала работы нужно — надежная сеть плюс подходящий гаджет, и вы сможете подключиться.

  16. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  17. 1XBet Promo Code – Vip Bonus as much as $130
    Enter the 1XBet promotional code: Code 1XBRO200 during sign-up in the App to avail exclusive rewards provided by 1xBet and get $130 as much as a full hundred percent, for placing bets along with a €1950 featuring free spin package. Open the app and proceed through the sign-up process.
    The 1XBet promo code: Code 1XBRO200 offers a great welcome bonus for new users — full one hundred percent as much as €130 during sign-up. Promotional codes act as the key to unlocking bonuses, also 1xBet’s promotional codes are no exception. By using this code, players have the chance of several promotions at different stages within their betting activity. Although you’re not eligible for the welcome bonus, 1xBet India guarantees its devoted players get compensated via ongoing deals. Visit the Offers page on the site regularly to remain aware regarding recent promotions designed for existing players.
    all 1xbet promo code
    What 1xBet bonus code is currently active at this moment?
    The promotional code for One X Bet equals Code 1XBRO200, which allows new customers joining the gambling provider to gain a bonus of 130 dollars. In order to unlock unique offers for casino and wagering, please input our bonus code for 1XBET in the registration form. To take advantage of this offer, potential customers must input the promotional code 1XBET during the registration process so they can obtain double their deposit amount on their initial deposit.

  18. 1xBet Promo Code – Vip Bonus maximum of $130
    Apply the One X Bet promotional code: 1XBRO200 when registering on the app to avail exclusive rewards provided by 1xBet for a welcome bonus as much as a full hundred percent, for wagering and a €1950 including 150 free spins. Launch the app and proceed through the sign-up procedure.
    This 1XBet promotional code: Code 1XBRO200 provides an amazing starter bonus for first-time users — 100% up to $130 upon registration. Promotional codes act as the key to obtaining extra benefits, plus One X Bet’s bonus codes are no exception. After entering this code, users can take advantage of various offers throughout their journey of their betting experience. Even if you don’t qualify to the starter reward, 1XBet India makes sure its regular customers receive gifts via ongoing deals. Visit the Offers page on their website often to stay updated on the latest offers designed for current users.
    1xbet promo code hack download
    What 1XBet promotional code is now valid today?
    The promo code relevant to 1XBet stands as 1xbro200, permitting novice players signing up with the betting service to gain an offer amounting to $130. In order to unlock exclusive bonuses related to games and bet placement, make sure to type this special code related to 1XBET in the registration form. To make use of this offer, prospective users must input the bonus code 1xbet during the registration process so they can obtain a full hundred percent extra for their first payment.

  19. Jamesred says:

    На этом сайте вы можете найти актуальные промокоды Melbet-промо.
    Примените коды при регистрации на платформе для получения максимальную награду за первое пополнение.
    Кроме того, здесь представлены промокоды для текущих акций и постоянных игроков.
    мелбет промокод
    Следите за обновлениями в рубрике акций, чтобы не упустить выгодные предложения от Melbet.
    Все промокоды проверяется на работоспособность, что гарантирует надежность при использовании.

  20. включи песню на ютубе

    Включайте онлайн-радиостанциями онлайн на нашем сайте бесплатно. Популярные радиостанции под ваше настроение.
    fm радио

  21. Michealher says:

    This online service features a wide range of pharmaceuticals for online purchase.
    Customers are able to quickly get health products with just a few clicks.
    Our product list includes everyday solutions and specialty items.
    All products is supplied through licensed suppliers.
    cenforce 2000
    We maintain user protection, with private checkout and timely service.
    Whether you’re managing a chronic condition, you’ll find safe products here.
    Visit the store today and experience convenient support.

  22. Wileyfew says:

    1XBet represents a leading sports betting platform.
    Featuring an extensive selection of sports, One X Bet meets the needs of millions globally.
    The 1XBet application is designed intended for Android as well as iOS bettors.
    https://arenafan.com/js/pgs/?chto_moghet_slomatysya_v_mashine.html
    You can download the 1xBet app from the official website and also Google Play Store on Android devices.
    Apple device owners, this software is available from the official iOS store with ease.

  23. Kennethframy says:

    ¡Hola aficionados a las apuestas !
    ObtГ©n tu bono sin depГіsito en minutos. Solo debes registrarte y los 25 giros gratis serГЎn tuyos. Comienza a jugar ahora mismo.
    RegГ­strate sin compromiso y consigue 25 giros. slots giros gratis sin deposito Prueba suerte en tus juegos favoritos.
    ВЎJuega con tiradas gratis slots sin depГіsito espaГ±a para nuevos jugadores – п»їhttps://25girosgratissindeposito.xyz/
    ¡Que tengas magníficas momentos emocionantes !

  24. Michealher says:

    Our platform features many types of pharmaceuticals for ordering online.
    Customers are able to easily get essential medicines without leaving home.
    Our range includes standard drugs and more specific prescriptions.
    Everything is acquired via trusted pharmacies.
    cenforce 200 mg
    Our focus is on quality and care, with data protection and prompt delivery.
    Whether you’re looking for daily supplements, you’ll find trusted options here.
    Start your order today and enjoy convenient access to medicine.

  25. Hello to our platform, where you can access premium content designed exclusively for grown-ups.
    Our library available here is suitable for individuals who are of legal age.
    Make sure that you meet the age requirement before proceeding.
    teen selfie
    Experience a one-of-a-kind selection of age-restricted materials, and dive in today!

  26. Wileyfew says:

    On this site can be found unique discount codes for online betting.
    These promocodes allow to receive extra incentives when placing bets on the website.
    All available special codes are constantly refreshed to ensure their validity.
    By applying these offers there is an opportunity to raise your chances on the gaming site.
    https://mobilemondaymelb.com/wp-content/pgs/?sovety_po_prohoghdeniyu_igry_soma_missiya_po_doroge_na_stanciyu_lyambda.html
    Plus, comprehensive manuals on how to redeem promo deals are offered for maximum efficiency.
    Note that particular bonuses may have particular conditions, so check them before activating.

  27. This website contains necessary info about techniques for turning into a cyber specialist.
    The materials are presented in a clear and concise manner.
    You will learn different tactics for entering systems.
    Besides, there are specific samples that demonstrate how to utilize these aptitudes.
    how to learn hacking
    Whole material is frequently refreshed to stay current with the latest trends in data safeguarding.
    Distinct concentration is directed towards real-world use of the mastered abilities.
    Consider that any undertaking should be carried out conscientiously and through ethical means only.

  28. People think about ending their life because of numerous causes, often resulting from severe mental anguish.
    A sense of despair can overwhelm their desire to continue. In many cases, isolation plays a significant role to this choice.
    Conditions like depression or anxiety can cloud judgment, preventing someone to recognize options to their pain.
    how to commit suicide
    Challenges such as financial problems, relationship issues, or trauma could lead a person toward this extreme step.
    Lack of access to help may leave them feeling trapped. It’s important to remember getting help is crucial.

  29. casino games says:

    Here, you can access a great variety of casino slots from top providers.
    Players can try out retro-style games as well as new-generation slots with vivid animation and bonus rounds.
    If you’re just starting out or a casino enthusiast, there’s always a slot to match your mood.
    play casino
    Each title are ready to play round the clock and compatible with desktop computers and mobile devices alike.
    All games run in your browser, so you can jump into the action right away.
    Platform layout is easy to use, making it convenient to explore new games.
    Register now, and discover the excitement of spinning reels!

  30. MichaelCoind says:

    Здесь вы найдете самые свежие информацию о событиях в стране и за рубежом. Новостная лента пополняется круглосуточно, что позволяет не упустить важные события о происходящем. Особое внимание уделяется различным аспектам жизни общества. Команда специалистов подготовили материалы, которые будут интересны всем неравнодушным людям. Дополнительно представлены экспертные комментарии, помогающие глубже понять современный контекст.
    https://forum.vercorsmacadamroller.fr/viewtopic.php?f=6&t=1769

  31. Looking to connect with qualified professionals available to handle short-term dangerous assignments.
    Require a freelancer to complete a hazardous assignment? Discover trusted laborers on our platform for urgent dangerous work.
    hitman for hire
    Our platform links clients with licensed workers prepared to take on hazardous one-off roles.
    Employ pre-screened freelancers for perilous tasks securely. Ideal when you need last-minute situations demanding specialized expertise.

  32. La nostra piattaforma offre il reclutamento di persone per lavori pericolosi.
    Gli utenti possono ingaggiare operatori competenti per missioni singole.
    Ogni candidato sono selezionati con cura.
    ordina l’uccisione
    Con il nostro aiuto è possibile consultare disponibilità prima di assumere.
    La professionalità è la nostra priorità.
    Sfogliate i profili oggi stesso per trovare il supporto necessario!

  33. The site makes it possible to get in touch with workers for one-time risky jobs.
    Visitors are able to efficiently set up help for unique requirements.
    All listed individuals have expertise in handling complex jobs.
    hitman-assassin-killer.com
    This service ensures private interactions between clients and freelancers.
    For those needing urgent assistance, our service is the perfect place.
    Submit a task and get matched with a skilled worker now!

  34. エロ 人形+?Zum Fenster herein kam eine Hand,ein P?ckchen darin die andereKrücke.

  35. ラブドール 150cm コメントに抵抗できませんでした。とてもよく書かれています!|

  36. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  37. 通过本平台,您可以聘请专门从事单次的高风险任务的人员。
    我们汇集大量可靠的从业人员供您选择。
    无论面对何种高风险任务,您都可以安全找到专业的助手。
    chinese-hitman-assassin.com
    所有作业人员均经过审核,保证您的隐私。
    服务中心注重安全,让您的任务委托更加无忧。
    如果您需要服务详情,请立即联系!

  38. Этот сайт — настоящий онлайн-площадка Bottega Венета с отправкой по стране.
    В нашем магазине вы можете заказать оригинальные товары Bottega Veneta с гарантией подлинности.
    Каждая покупка идут с официальной гарантией от бренда.
    bottega-official.ru
    Отправка осуществляется быстро в по всей территории России.
    Платформа предлагает безопасные способы оплаты и лёгкий возврат.
    Выбирайте официальном сайте Боттега Венета, чтобы быть уверенным в качестве!

  39. В этом разделе вы можете найти действующее зеркало 1xBet без блокировок.
    Оперативно обновляем ссылки, чтобы обеспечить свободное подключение к сайту.
    Переходя через зеркало, вы сможете пользоваться всеми функциями без перебоев.
    1xbet-official.live
    Наш сайт облегчит доступ вам безопасно получить свежее зеркало 1xBet.
    Мы заботимся, чтобы каждый пользователь имел возможность получить полный доступ.
    Проверяйте новые ссылки, чтобы не терять доступ с 1xBet!

  40. This platform makes it possible to find professionals for temporary high-risk missions.
    Visitors are able to securely request services for unique operations.
    All listed individuals are trained in managing intense tasks.
    hitman for hire
    Our platform ensures discreet connections between users and specialists.
    If you require fast support, our service is ready to help.
    Post your request and connect with an expert today!

  41. carbox30.ru says:

    Приобретение туристического полиса при выезде за границу — это обязательное условие для обеспечения безопасности туриста.
    Страховка гарантирует расходы на лечение в случае обострения болезни за границей.
    К тому же, сертификат может включать возмещение затрат на транспортировку.
    icforce.ru
    Некоторые государства настаивают на предъявление страховки для пересечения границы.
    Без наличия документа госпитализация могут стать дорогими.
    Оформление полиса до поездки

  42. Charlesfeevy says:

    Лето 2025 года обещает быть стильным и инновационным в плане моды.
    В тренде будут свободные силуэты и игра фактур.
    Модные цвета включают в себя неоновые оттенки, подчеркивающие индивидуальность.
    Особое внимание дизайнеры уделяют аксессуарам, среди которых популярны макросумки.
    https://lepodium.blogchaat.com/30281514/lepodium-%D0%B2%D0%B0%D1%88-%D0%BF%D1%80%D0%BE%D0%B2%D0%BE%D0%B4%D0%BD%D0%B8%D0%BA-%D0%B2-%D0%BC%D0%B8%D1%80%D0%B5-%D0%BB%D1%8E%D0%BA%D1%81%D0%BE%D0%B2%D0%BE%D0%B9-%D0%BC%D0%BE%D0%B4%D1%8B
    Возвращаются в моду элементы 90-х, через призму сегодняшнего дня.
    На улицах мегаполисов уже можно увидеть смелые решения, которые поражают.
    Экспериментируйте со стилем, чтобы создать свой образ.

  43. casino games says:

    This website, you can discover a wide selection of slot machines from famous studios.
    Visitors can try out traditional machines as well as feature-packed games with stunning graphics and interactive gameplay.
    Whether you’re a beginner or a seasoned gamer, there’s something for everyone.
    casino
    Each title are instantly accessible round the clock and optimized for desktop computers and mobile devices alike.
    All games run in your browser, so you can jump into the action right away.
    Platform layout is easy to use, making it simple to browse the collection.
    Register now, and discover the excitement of spinning reels!

Leave a Reply

Your email address will not be published. Required fields are marked *