Flea
Flea

Reputation: 1528

Custom Control Property from DynamicResource

I am trying to combine two concepts, a extending a standard control, and application theming by extending the Picker control and adding in a TextColor property and having a custom renderer on the Android (and iOS eventually) platform. I can successfully set the TextColor property and have it display the color if it is set statically as the following:

<controls:ExtendedPicker TextColor="Red"/>

The final step in this process is to be able to pull the property from a Dynamic Resource and have it able to be changed at runtime.

<controls:ExtendedPicker Style="{DynamicResource pickerStyle}"/>

and then, in the Application.Resources ResourceDictionary:

<Color x:Key="textColor"/>
...
<Style x:Key="pickerStyle" TargetType="controls:ExtendedPicker">
  <Setter Property="TextColor" Value="{DynamicResource textColor}" />
</Style>

Note that this method for choosing TextColor works with native controls such as Label. The code compiles and runs but doesn't seem to pick up the dynamic resource color setting when changed at runtime. I am assuming that this is something that I am missing handling this in my custom renderer but am at a loss as to what to look for.

Upvotes: 1

Views: 922

Answers (2)

SushiHangover
SushiHangover

Reputation: 74094

Override the OnElementChanged your custom platform-dependent render and you can get a reference to your Xamarin.Forms-based custom (subclassed) control via the e.NewElement property.

So you can cast e.NewElement as your custom control and get that classes properties (your custom Picker color that you assigned in the XAML):

(e.NewElement as ExtendedPicker).TextColor;

Something like this:

    protected override void OnElementChanged (ElementChangedEventArgs< ExtendedPicker> e)
    {
        base.OnElementChanged (e);

        if (Control == null) {
           ~~~~~~
        }
        if (e.OldElement != null) {
           ~~~~~~
        }
        if (e.NewElement != null) {
            var myPickerControl = (e.NewElement as ExtendedPicker). TextColor;
            // Assign `myPickerControl` to your UI dependent control
            ~~~~~~~
        }
    }

Upvotes: 0

Flea
Flea

Reputation: 1528

To handle this at run-time I had to override the

OnElementPropertyChanged 

method in the custom renderer rather than the

OnElementChanged 

method.

Upvotes: 1

Related Questions