Set DatePicker text color according to IsEnabled property

765 Views Asked by At

In one of my Xamarin.Forms apps I want to change the text color of a DatePicker according to the IsEnabled property.

I tried two known ways:

1) Using a style

In App.xaml:

<Style x:Key="DatePickerStyle" TargetType="DatePicker">
    <Style.Triggers>
        <Trigger TargetType="DatePicker" Property="IsEnabled" Value="True">
            <Setter Property="TextColor" Value="Blue" />
        </Trigger>
        <Trigger TargetType="DatePicker" Property="IsEnabled" Value="False">
            <Setter Property="TextColor" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

In View.xaml:

<DatePicker IsEnabled="{Binding IsEnabled}" Style="{StaticResource DatePickerStyle}" ... />

2) Adding the trigger in XAML

<ViewCell>
    <DatePicker IsEnabled="{Binding IsEnabled}" ...>
        <DatePicker.Triggers>
            <Trigger TargetType="DatePicker" Property="IsEnabled" Value="True">
                <Setter Property="TextColor" Value="Blue" />
            </Trigger>
            <Trigger TargetType="DatePicker" Property="IsEnabled" Value="False">
                <Setter Property="TextColor" Value="Red" />
            </Trigger>
        </DatePicker.Triggers>
    </DatePicker>
</ViewCell>

Both ways lead to a "System.InvalidOperationException: bindable not an instance of AssociatedType" exception.

Is it possible to change the text color of a picker with an applied style that contains a trigger at the IsEnabled property? Will a behavior be a better way to go?

1

There are 1 best solutions below

0
Cem.S On

I faced a similar issue with DatePicker and found no explanation on Xamarin forums or msdn. I have finally used the following workaround and it works

<Style TargetType="DatePicker">
            <Setter Property="VisualStateManager.VisualStateGroups">
                <VisualStateGroupList x:Name="CommonStates">
                    <VisualStateGroup>
                        <VisualState x:Name="Normal" />
                        <VisualState x:Name="Disabled">
                            <VisualState.Setters>
                                <Setter Property="TextColor" Value="LightGray" />
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateGroupList>
            </Setter>
        </Style>

See also Visual State Manager.