Advanced .NET MAUI Topic: Visual State

With the release of my newest book, .NET MAUI For C# Developers, I’m pleased to present occasional posts on advanced topics. If you are just starting out, however, you may want to take a look at my previous 15 part series in which I learn .NET MAUI or my second series that uses the app (Forget Me Not) that we’ll be using here. Finally, you can find my presentations on .NET MAUI and advanced .NET MAUI on YouTube, here.

Managing Visual State

Every VisualElement has a Visual State. For example, does the VisualElement have focus? Is it selected? Xaml allows you to change the presentation of that VisualElement (e.g., a button) based on that state.

The object that sets visual properties on a VisualElement based on its state is the Visual State Manager. The Visual State Manager selects from among a set of VisualStates and displays the view according to styles that you create.

Defining the common visual states

.NET MAUI defines a set of common visual states:

  • Normal
  • Disabled
  • Has focus
  • Is selected
  • Mouse over (for Windows and MacOs)

.NET MAUI also allows you to define your own visual states.

Button VisualState example

When you first come to the Login page in Forget Me Not, the Submit button is disabled. Once you fill in the two fields of Your Email and Password, the button should turn light green. If you tab to the button it should signify that it has the focus by turning fully green. You can do all this declarative with Visual States.

Visual State and Styles

You can set the visual state on an individual button, or, as we will do here, you can put the visual state XAML into a style and apply it to all the buttons. Here is the complete Style for buttons:

<Style x:Key="LoginButton" TargetType="Button"> 

    <Setter Property="Margin" Value="0,20,0,0" />

    <Setter Property="TextColor" Value="Black" />

    <Setter Property="WidthRequest" Value="125" />

    <Setter Property="VisualStateManager.VisualStateGroups"> 

        <VisualStateGroupList> 

            <VisualStateGroup x:Name="CommonStates"> 

                <VisualState x:Name="Normal"> 

                    <VisualState.Setters> 

                        <Setter Property="BackgroundColor" Value="LightGreen" />

                    </VisualState.Setters>

                </VisualState>

                <VisualState x:Name="Focused">

                    <VisualState.Setters>

                        <Setter Property="BackgroundColor" Value="Green" />

                    </VisualState.Setters>

                </VisualState>

                <VisualState x:Name="Disabled">

                    <VisualState.Setters>

                        <Setter Property="BackgroundColor" Value="Gray" />

                    </VisualState.Setters>

                </VisualState>

            </VisualStateGroup>

        </VisualStateGroupList>

    </Setter>

</Style>

We start by declaring a normal Style, in this case implicit for every button. You may have one or more groups of visual states (we have one). The first group (and in this case the only one) is the CommonStates

We declare each VisualState in turn (here we’re starting with Normal). For each state, we can declare a set of Setters. Our first (and in this case only) Setter sets the BackgroundColor property

We then go on to set the Setters for all the other states. Notice that we did not set the Setter for PointerOver, which means that, on Windows and macOS, if you hover the mouse over the button there will be no change.

.NET MAUI defines specialized visual states for controls. For example, Button adds the Pressed state while CheckBox adds the IsChecked state and CollectionViews adds Selected.

The .NET MAUI community toolkit provides further help for managing the appearance and behavior of your app with a large collection of Behaviors.

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, is now available wherever you buy your books. 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 .NET MAUI and tagged , , . Bookmark the permalink.

126 Responses to Advanced .NET MAUI Topic: Visual State

  1. Здесь можно получить мессенджер-бот “Глаз Бога”, что собрать всю информацию по человеку по публичным данным.
    Бот функционирует по фото, используя публичные материалы в сети. С его помощью осуществляется пять пробивов и полный отчет по фото.
    Платфор ма обновлен согласно последним данным и охватывает аудио-материалы. Бот сможет узнать данные в соцсетях и предоставит сведения за секунды.
    глаз бога информация о человеке
    Данный инструмент — помощник для проверки людей удаленно.

  2. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  3. Коллекция Nautilus, созданная Жеральдом Гентой, сочетает элегантность и прекрасное ремесленничество. Модель Nautilus 5711 с самозаводящимся механизмом имеет энергонезависимость до 2 дней и корпус из белого золота.
    Восьмиугольный безель с округлыми гранями и синий солнечный циферблат подчеркивают уникальность модели. Браслет с интегрированными звеньями обеспечивает удобную посадку даже при активном образе жизни.
    Часы оснащены функцией даты в позиции 3 часа и сапфировым стеклом.
    Для сложных модификаций доступны хронограф, лунофаза и функция Travel Time.
    patek-philippe-nautilus.ru
    Например, модель 5712/1R-001 из розового золота с механизмом на 265 деталей и запасом хода до 48 часов.
    Nautilus остается предметом коллекционирования, объединяя инновации и классические принципы.

  4. 164802 232622I undoubtedly didnt comprehend that. Learnt some thing new nowadays! Thanks for that. 47888

  5. pinco indir says:

    189226 561213Man you legend. return see my web site, you must get pleasure from it. 122422

  6. ufa11k says:

    578022 914013But wanna comment on couple of common points, The web site style is perfect, the content material is really great : D. 45361

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

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

  9. Монтаж систем видеонаблюдения позволит безопасность помещения в режиме 24/7.
    Продвинутые системы обеспечивают высокое качество изображения даже в ночных условиях.
    Наша компания предоставляет различные варианты устройств, подходящих для бизнеса и частных объектов.
    videonablyudeniemoskva.ru
    Качественный монтаж и сервисное обслуживание превращают решение простым и надежным для каждого клиента.
    Оставьте заявку, чтобы получить лучшее решение по внедрению систем.

  10. Коллекция Nautilus, созданная Жеральдом Гентой, сочетает элегантность и высокое часовое мастерство. Модель Nautilus 5711 с автоматическим калибром 324 SC имеет энергонезависимость до 2 дней и корпус из нержавеющей стали.
    Восьмиугольный безель с плавными скосами и синий солнечный циферблат подчеркивают неповторимость модели. Браслет с H-образными элементами обеспечивает комфорт даже при повседневном использовании.
    Часы оснащены индикацией числа в позиции 3 часа и сапфировым стеклом.
    Для сложных модификаций доступны секундомер, вечный календарь и функция Travel Time.
    Посмотреть часы Patek Nautilus на этом сайте
    Например, модель 5712/1R-001 из красного золота 18K с калибром повышенной сложности и запасом хода на двое суток.
    Nautilus остается символом статуса, объединяя современные технологии и классические принципы.

  11. TyroneSum says:

    Данный портал предлагает свежие новости со всего мира.
    Здесь доступны события из жизни, бизнесе и разных направлениях.
    Новостная лента обновляется ежедневно, что позволяет не пропустить важное.
    Понятная навигация ускоряет поиск.
    https://hypebeasts.ru
    Все публикации предлагаются с фактчеком.
    Редакция придерживается честной подачи.
    Следите за обновлениями, чтобы быть в центре внимания.

  12. pg168 says:

    721182 795379I was suggested this weblog by way of my cousin. Im no longer confident whether or not this put up is written by him as nobody else realize such detailed about my trouble. You are amazing! Thanks! 387353

  13. pg168 says:

    557706 10266Some actually excellent articles on this website , thankyou for contribution. 622910

  14. 410725 316979I genuinely like your writing style, excellent information , thankyou for putting up : D. 425958

  15. 409644 656936This web internet site is typically a walk-through its the data you wished concerning this and didnt know who ought to. Glimpse here, and youll undoubtedly discover it. 827362

  16. DonaldGyday says:

    Die Royal Oak 16202ST vereint ein 39-mm-Edelstahlgehäuse mit einem ultradünnen Profil und dem automatischen Werk 7121 für lange Energieautonomie.
    Das „Bleu Nuit“-Zifferblatt mit leuchtenden Stundenmarkern und Royal-Oak-Zeigern wird durch eine kratzfeste Saphirabdeckung mit Antireflex-Beschichtung geschützt.
    Neben praktischer Datumsanzeige bietet die Uhr bis 5 ATM geschützte Konstruktion und ein integriertes Stahlarmband mit verstellbarem Verschluss.
    Audemars Royal Oak 15450 st damenuhren
    Die oktogonale Lünette mit verschraubten Edelstahlteilen und die polierte Oberflächenkombination zitieren den 1972er Klassiker.
    Als Teil der „Jumbo“-Linie ist die 16202ST eine horlogerie-Perle mit einem Preis ab ~75.900 €.

  17. binance says:

    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.

  18. KennethFus says:

    Стальные резервуары используются для сбора нефтепродуктов и соответствуют стандартам давления до 0,04 МПа.
    Горизонтальные емкости изготавливают из черной стали Ст3 с антикоррозийным покрытием.
    Идеальны для промышленных объектов: хранят бензин, керосин, мазут или биодизель.
    Деаэратор атмосферный ДА-50
    Двустенные резервуары обеспечивают экологическую безопасность, а подземные модификации подходят для разных условий.
    Заводы предлагают типовые решения объемом до 500 м³ с монтажом под ключ.

  19. Peterbup says:

    Die Royal Oak 16202ST kombiniert ein 39-mm-Edelstahlgehäuse mit einem ultradünnen Design von nur 8,1 mm Dicke.
    Ihr Herzstück bildet das automatische Manufakturwerk 7121 mit erweitertem Energievorrat.
    Der smaragdene Farbverlauf des Zifferblatts wird durch das feine Guillochierungen und die Saphirglas-Abdeckung mit blendschutzbeschichteter Oberfläche betont.
    Neben klassischer Zeitmessung bietet die Uhr ein Datumsfenster bei 3 Uhr.
    Piguet Audemars Royal Oak 15202st uhren
    Die bis 5 ATM geschützte Konstruktion macht sie für sportliche Einsätze geeignet.
    Das geschlossene Stahlband mit faltsicherer Verschluss und die achtseitige Rahmenform zitieren das ikonische Royal-Oak-Erbe aus den 1970er Jahren.
    Als Teil der legendären Extra-Thin-Reihe verkörpert die 16202ST meisterliche Uhrmacherkunst mit einem Wertanlage für Sammler.

  20. Peterbup says:

    Die Royal Oak 16202ST kombiniert ein rostfreies Stahlgehäuse von 39 mm mit einem ultradünnen Design von nur 8,1 mm Dicke.
    Ihr Herzstück bildet das neue Kaliber 7121 mit erweitertem Energievorrat.
    Der smaragdene Farbverlauf des Zifferblatts wird durch das feine Guillochierungen und die Saphirglas-Abdeckung mit Antireflexbeschichtung betont.
    Neben klassischer Zeitmessung bietet die Uhr ein praktisches Datum bei Position 3.
    Audemars Piguet Royal Oak 15407st damenuhr
    Die 50-Meter-Wasserdichte macht sie für sportliche Einsätze geeignet.
    Das integrierte Edelstahlarmband mit verstellbarem Dornschließe und die achtseitige Rahmenform zitieren das ikonische Royal-Oak-Erbe aus den 1970er Jahren.
    Als Teil der legendären Extra-Thin-Reihe verkörpert die 16202ST meisterliche Uhrmacherkunst mit einem Wertanlage für Sammler.

  21. 834715 491551Remarkable blog layout here. Was it hard creating a nice seeking website like this? 412267

  22. EddieInjub says:

    The Audemars Piguet Royal Oak, redefined luxury watchmaking with its signature angular case and stainless steel craftsmanship .
    Available in classic stainless steel to skeleton dials , the collection merges avant-garde design with horological mastery.
    Priced from $20,000 to over $400,000, these timepieces cater to both seasoned collectors and newcomers seeking investable art .
    New AP Royal Oak 26240 or boutique
    The Royal Oak Offshore set benchmarks with robust case constructions, showcasing Audemars Piguet’s technical prowess .
    Thanks to ultra-thin calibers like the 2385, each watch epitomizes the brand’s commitment to excellence .
    Explore certified pre-owned editions and historical insights to deepen your horological expertise with this modern legend .

  23. EddieInjub says:

    The Audemars Piguet Royal Oak, revolutionized luxury watchmaking with its signature angular case and bold integration of sporty elegance.
    Available in limited-edition sand gold to diamond-set variants, the collection merges avant-garde design with precision engineering .
    Priced from $20,000 to over $400,000, these timepieces cater to both luxury enthusiasts and newcomers seeking wearable heritage.
    All Audemars Oak 26240 or photos
    The Perpetual Calendar models push boundaries with innovative complications , embodying Audemars Piguet’s relentless innovation.
    With ultra-thin calibers like the 2385, each watch epitomizes the brand’s legacy of craftsmanship.
    Explore exclusive releases and historical insights to deepen your horological expertise with this timeless icon .

  24. RobertErymn says:

    Explore the iconic Patek Philippe Nautilus, a horological masterpiece that merges sporty elegance with refined artistry.
    Launched in 1976 , this legendary watch redefined high-end sports watches, featuring distinctive octagonal bezels and horizontally grooved dials .
    From stainless steel models like the 5990/1A-011 with a 55-hour energy retention to opulent gold interpretations such as the 5811/1G-001 with a blue gradient dial , the Nautilus suits both avid enthusiasts and casual admirers.
    Certified Patek Philippe Nautilus 5711 watch
    Certain diamond-adorned versions elevate the design with gemstone accents, adding unparalleled luxury to the timeless profile.
    With market values like the 5726/1A-014 at ~$106,000, the Nautilus remains a prized asset in the world of premium watchmaking.
    Whether you seek a historical model or modern redesign, the Nautilus embodies Patek Philippe’s legacy of excellence .

  25. 360811 836756There is noticeably a great deal to realize about this. I suppose you created certain nice points in functions also. 430478

  26. 700655 856532superb post. Neer knew this, appreciate it for letting me know. 317273

Leave a Reply to EddieInjub Cancel reply

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