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

67 Responses to .NET MAUI Triggers

  1. cd alarm says:

    On this site showcases CD player radio alarm clocks from top providers.
    Here you’ll discover sleek CD units with digital radio and two alarm settings.
    Most units offer aux-in ports, device charging, and battery backup.
    Available products covers affordable clocks to luxury editions.
    cd player alarm clock radio
    All clocks include nap modes, rest timers, and illuminated panels.
    Buy now through online retailers and no extra cost.
    Find the perfect clock-radio-CD setup for bedroom daily routines.

  2. DavidTwelt says:

    Our platform offers off-road vehicle rentals on the island of Crete.
    You can safely book a ride for exploration.
    In case you’re looking to discover coastal trails, a buggy is the ideal way to do it.
    https://www.behance.net/buggycrete
    Our rides are safe and clean and can be rented for full-day bookings.
    Booking through this site is fast and comes with affordable prices.
    Hit the trails and discover Crete from a new angle.

  3. Jamescrumn says:

    This online pharmacy offers a broad selection of medications with competitive pricing.
    You can find all types of medicines suitable for different health conditions.
    We work hard to offer trusted brands while saving you money.
    Speedy and secure shipping provides that your medication gets to you quickly.
    Take advantage of ordering medications online through our service.
    vidalista reviews

  4. MichaelVilla says:

    Did you know that over 60% of patients make dangerous pharmaceutical mishaps stemming from lack of knowledge?

    Your wellbeing is your most valuable asset. All treatment options you consider plays crucial role in your long-term wellbeing. Being informed about medical treatments should be mandatory for optimal health outcomes.
    Your health isn’t just about taking pills. Each drug interacts with your biological systems in specific ways.

    Remember these critical facts:
    1. Taking incompatible prescriptions can cause health emergencies
    2. Over-the-counter allergy medicines have potent side effects
    3. Skipping doses reduces effectiveness

    To avoid risks, always:
    ✓ Check compatibility using official tools
    ✓ Read instructions thoroughly prior to using any medication
    ✓ Consult your doctor about correct dosage

    ___________________________________
    For reliable medication guidance, visit:
    https://www.pinterest.com/pin/879609370963830780/

  5. play casino says:

    This website, you can find lots of online slots from leading developers.
    Players can enjoy classic slots as well as feature-packed games with high-quality visuals and exciting features.
    Whether you’re a beginner or a seasoned gamer, there’s a game that fits your style.
    slot casino
    Each title are instantly accessible round the clock and optimized for PCs and tablets alike.
    All games run in your browser, so you can jump into the action right away.
    Site navigation is easy to use, making it quick to find your favorite slot.
    Register now, and enjoy the excitement of spinning reels!

  6. Da h?tten Sie sehen sollen,wiedie Augen des jungen Mannes aufleuchteten und mit welcher Eilfertigkeiter uns nach einem geeigneten Pl?tzchen hinführte.セックス 人形

  7. Donalddiape says:

    Espectro de vibracion
    Sistemas de balanceo: esencial para el operacion estable y efectivo de las equipos.

    En el campo de la innovacion moderna, donde la eficiencia y la fiabilidad del aparato son de gran importancia, los sistemas de balanceo cumplen un rol esencial. Estos sistemas adaptados estan concebidos para balancear y regular componentes rotativas, ya sea en dispositivos industrial, medios de transporte de traslado o incluso en equipos domesticos.

    Para los expertos en mantenimiento de sistemas y los tecnicos, manejar con dispositivos de ajuste es importante para promover el funcionamiento suave y estable de cualquier mecanismo rotativo. Gracias a estas herramientas innovadoras innovadoras, es posible reducir notablemente las vibraciones, el sonido y la presion sobre los sujeciones, mejorando la longevidad de partes valiosos.

    Asimismo importante es el tarea que cumplen los sistemas de equilibrado en la asistencia al usuario. El ayuda experto y el soporte constante aplicando estos sistemas habilitan dar soluciones de optima excelencia, incrementando la contento de los compradores.

    Para los duenos de negocios, la inversion en sistemas de equilibrado y dispositivos puede ser importante para incrementar la productividad y desempeno de sus aparatos. Esto es principalmente trascendental para los empresarios que manejan modestas y pequenas emprendimientos, donde cada punto vale.

    Por otro lado, los equipos de calibracion tienen una gran uso en el area de la fiabilidad y el control de nivel. Permiten detectar probables errores, evitando intervenciones caras y danos a los dispositivos. Mas aun, los indicadores obtenidos de estos dispositivos pueden usarse para perfeccionar metodos y mejorar la visibilidad en motores de investigacion.

    Las campos de implementacion de los equipos de calibracion cubren numerosas areas, desde la manufactura de bicicletas hasta el control ambiental. No interesa si se refiere de extensas fabricaciones industriales o limitados espacios caseros, los equipos de balanceo son necesarios para promover un desempeno optimo y sin riesgo de interrupciones.

  8. Dustinser says:

    Traditional timepieces will continue to be relevant.
    They embody tradition and offer a human touch that digital devices simply fail to offer.
    A single watch is powered by fine movements, making it both accurate and elegant.
    Watch enthusiasts value the craft behind them.
    https://itechfy.com/tech/maxbezel-the-ultimate-destination-for-luxury-watch-enthusiasts/
    Wearing a mechanical watch is not just about practicality, but about making a statement.
    Their styles are classic, often passed from lifetime to legacy.
    All in all, mechanical watches will remain icons.

  9. And Frederick,from her passionately loved bridegroom,ダッチワイフ エロ

  10. slot casino says:

    This website, you can discover a great variety of slot machines from leading developers.
    Players can enjoy retro-style games as well as modern video slots with vivid animation and exciting features.
    If you’re just starting out or a seasoned gamer, there’s always a slot to match your mood.
    slot casino
    Each title are available anytime and optimized for PCs and smartphones alike.
    You don’t need to install anything, so you can get started without hassle.
    Platform layout is user-friendly, making it quick to find your favorite slot.
    Sign up today, and dive into the thrill of casino games!

  11. Wonderful work! This is the type of info that should be shared around the internet. Shame on the search engines for not positioning this post higher! Come on over and visit my website . Thanks =)

  12. Despite Ding being much decrease on time, it was Nepomniachtchi who allowed his opponent to consolidate his slight edge.

  13. Camille Co has beloved vogue for so long as she’s been alive, and you may see that dedication come through in each certainly one of her posts.

  14. Retired pay and Survivor Benefit Plan funds are tax-free.

  15. The workforce should have a pacesetter, and you might want to use your emergency preparedness crew chief for this place, as they’re already educated in the event of crises.

  16. Wear it to workplace parties or just hanging out with your gang of ladies.

  17. Hairstyles says:

    Almost all of what you state is supprisingly appropriate and that makes me ponder why I hadn’t looked at this with this light before. This article truly did turn the light on for me personally as far as this specific subject matter goes. But there is actually one point I am not too cozy with so whilst I make an effort to reconcile that with the central idea of your position, permit me see exactly what the rest of the visitors have to say.Well done.

  18. So, whether or not it is about spending some quality time with all the cherished ones or doing Aartis on the Puja Mandaps or gorging on some delicacies collectively, one thing that is still mandatory is dressing up within the prettiest and trendy put on to look good.

  19. The flights grew to become popular with Cincinnati firms.

  20. Nashville received by just one vote.

  21. Workplace of the town Administrator – Chief Monetary Officer, City of Bordentown.

  22. Clark Caves was born Feb 18, 1911, in Okay.

  23. They haven’t got cash to place an order.

  24. Столкнувшись с проблемой наличия клопов, важно не откладывать решение.
    Мы предлагаем профессиональную помощь по обработке от клопов.
    Наша компания использует современные технологии, обеспечивая полное избавление от клопов.
    Мы поможем вам вернуть безопасность в ваш дом.

    борьба с клопами
    ;

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

  26. マガこれでしか味わえない「マジ肌」は手に吸い付くような、オナドール本物の肌の質感が魅力です。

  27. 1000’s of years after his demise, Malgus was nonetheless remembered as some of the highly effective Sith Lords to have ever lived.

  28. Hello, I believe your website could be having web
    browser compatibility problems. When I look at your
    blog in Safari, it looks fine however, when opening in I.E., it has some overlapping issues.
    I just wanted to provide you with a quick heads up! Apart from that, great website!

  29. Thanks for sharing your thoughts about retro bowl 2. Regards

  30. These three openings have some similarities; a few of the quieter lines in the Vienna and Bishop’s Opening can transpose to positional variations of the King’s Gambit Declined, when White plays f2-f4 earlier than enjoying Nf3.

  31. com to anyone looking for a high-quality,com has been a truly remarkable experience.美人 セックス

  32. Nelson, Claus A.: (TS: 1878-1960; shared stone w/ Minnie R.) See SLE page 538-9: Claus Alfred Nelson was born in Kungsater Elfsborg Lan, Sweden in 1878.

  33. Set in the Center Ages, the sport was released on February 14, 2012, as a sequel to 2004’s Crusader Kings.

  34. The median age was 40.3 years.

  35. Final-minute weddings can still profit from the expertise of a Vacation spot Wedding ceremony Planner in Delhi.

  36. making it straightforward for readers like myself to apply them to real-world situations.The balance you maintained between theoretical concepts and practical applications was particularly commendable.ダッチワイフ

  37. The tune achieved a lot of its fame when it was carried out by Johnny Cash in his Folsom Prison live performance (At Folsom Prison).

  38. Philadelphia on the Fly, printed in 2005, and Small Fry: The Lure of the Little, printed in 2009 comprise essays by Ron P. Swegman describing the experience of fly fishing alongside the city Schuylkill River in the twenty first century.

  39. This aquamarine ring is a perfect alternative for individuals who appreciate refined beauty and graceful fashion.

  40. A member of Green Bay A. M. E. Church, she was the secretary and a Sunday college trainer.

  41. Utilizing one multitool destroys a certain share of this hardness – say, 20.

  42. This program is named Naira4all, the guaranty methods to make money online from Nigeria, the only reliable on-line cash making opportunity in Nigeria.

  43. In summer 1782, a brand new British government got here to energy, who still hoped to realize a reconciliation with the American colonies.

  44. Nevertheless, to my surprise, licensing know-how did not save us on a regular basis I would hoped it will.

  45. That you may learn words and phrases use your individual language your personal language studying and writing studying and writing, and writing abilities, studying and writing studying and writing discuss your life, spanish around the time, the time you group and non-public, our spanish lessons our spanish lessons, are native audio system can select from studying spanish on-line provide you with our spanish programs will show you how to you can learn with Spanish.

Leave a Reply

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