0
votes

I think my code is self explanatory:

<Label Style="{DynamicResource labelStyle}"
           HorizontalTextAlignment="End" Text="{Binding message}">
      <OnPlatform x:TypeArguments="Color">
        <OnPlatform.iOS>
          {DynamicResource rightBubbleFontColor}
        </OnPlatform.iOS>
        <OnPlatform.Android>
            {DynamicResource rightBubbleFontColor}
        </OnPlatform.Android>
          <OnPlatform.Android>
            {StaticResource rightBubbleFontColor}
        </OnPlatform.Android>
      </OnPlatform>
    </Label>

I'm trying to dynamically bind a color to the label. Depending on the current platform, it has to be another type of resource (DynamicResource or StaticResource).

I get this exception when trying to build the solution:

System.ArgumentException: An item with the same key has already been added.

UPDATE

I now have this code:

<Label Style="{DynamicResource labelStyle}"
           HorizontalTextAlignment="End" Text="{Binding message}">
      <Label.TextColor>
        <OnPlatform 
          x:Key="RightBubbleFontColor" 
          x:TypeArguments="Color"
          iOS="{DynamicResource rightBubbleFontColor}"
          Android="{DynamicResource rightBubbleFontColor}"
          WinPhone="{StaticResource rightBubbleFontColor}">
        </OnPlatform>
      </Label.TextColor>
    </Label>

And I get the following error message: Object reference not set to an instance of an object.

When I replace the binding to a color it works.

Working example:

<Label Style="{DynamicResource labelStyle}"
           HorizontalTextAlignment="End" Text="{Binding message}">
      <Label.TextColor>
        <OnPlatform 
          x:Key="RightBubbleFontColor" 
          x:TypeArguments="Color"
          iOS="Red"
          Android="Green"
          WinPhone="Blue">
        </OnPlatform>
      </Label.TextColor>
    </Label>

So it has to be an issue with the way I'm trying to bind this I guess.

EDIT

Asked a new question to describe the problem better: https://stackguides.com/questions/39852888/xamarin-forms-use-dynamicresource-or-staticresource-depending-on-os

1
Looks like the DynamicResource issue is something that's been around since at least April... forums.xamarin.com/discussion/65252/… - Ryan Alford

1 Answers

2
votes

You have two <OnPlatform.Android> elements. I'm assuming the last would be <OnPlatform.WinPhone>.

EDITED

Now that you have that fixed, maybe try this for it to actually work?

<OnPlatform 
   x:Key="BubbleTextColor" 
   x:TypedArguments="Color"
   iOS="{DynamicResource rightBubbleFontColor}"
   Android="{DynamicResource rightBubbleFontColor}"
   WinPhone="{StaticResource rightBubbleFontColor}" />

Then bind it where necessary.

Not sure if it will work any differently than what you already have, but I guess it's worth a shot.