Home > Back-end >  Applying styles from resources with triggers MAUI
Applying styles from resources with triggers MAUI

Time:10-11

I want to apply some styles (colors) in my MAUI app, to the border that is wrapped around the entry. When entry is focused I want its border to be blue and Grey when unfocused. Is it possible to do this with triggers in Styles.xaml?

 <Border Style="{StaticResource LogInEntryBoarder}">
      <Entry Placeholder="{x:Static res:AppRes.E_mail}" Focused="Entry_Focused" x:Name="Email_Entry" Style="{StaticResource LoginEntry}"/>
 </Border>
private void Entry_Focused(object sender, FocusEventArgs e)
{
    Border border = (Border)((Entry)sender).Parent;
    border.Focus();
}
<Style TargetType="Border" x:Key="LogInEntryBoarder">
        <Style.Triggers>
            <Trigger TargetType="Border" Property="IsFocused" Value="True">
                <Setter Property="Stroke" Value="{AppThemeBinding Light={StaticResource Fifth}, Dark={StaticResource Gray500}}"></Setter>
            </Trigger>
        </Style.Triggers>
        <Setter Property="Stroke" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
        <Setter Property="BackgroundColor" Value="{AppThemeBinding Light={StaticResource Tertiary}, Dark={StaticResource Gray500}}" />
        <Setter Property="StrokeShape" Value="RoundRectangle 2,2,2,2"/>
        <Setter Property="Padding" Value="6,0,0,0"/>
        <Setter Property="StrokeThickness" Value="1"/>
    </Style>

CodePudding user response:

You probably want to do something like this:

<Border Style="{StaticResource LogInEntryBoarder}">
    <Entry Placeholder="{x:Static res:AppRes.E_mail}" Focused="Entry_Focused" x:Name="Email_Entry" Style="{StaticResource LoginEntry}"/>
    <Border.Triggers>
        <DataTrigger TargetType="Border"
                     Binding="{Binding Source={x:Reference Email_Entry}, Path=IsFocused}"
                     Value="True">
            <Setter Property="Stroke" Value="Blue"/>
        </DataTrigger>
        <DataTrigger TargetType="Border"
                     Binding="{Binding Source={x:Reference Email_Entry}, Path=IsFocused}"
                     Value="False">
            <Setter Property="Stroke" Value="Grey"/>
        </DataTrigger>
    </Border.Triggers>
</Border>

It is explained here: https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/triggers#data-triggers

You cannot do it with Styles directly, because you need to bind to a different View element. I think that the DataTrigger approach is the appropriate way to go here.

  • Related