I have a ComboBox with a custom theme I wrote, and I get the error message "Cannot animate (0).(1) on an immutable object." This specifically happens when I set its selectedindex
after the user selects one of the options in the combobox.
Doing some research online, I found that this is a common issue with databound items or dynamic resources. I'm not using any databound resources, but what I think is happening is since the combobox is collapsed, it tries to set the state of a button that doesn't exist. I narrowed it down to this code:
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="Border" Property="Background" Value="{DynamicResource spPressedStateBrush}" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Border" Property="Background" Value="{DynamicResource spOverStateBrush}" />
</Trigger>
</ControlTemplate.Triggers>
Which depends on these Dynamic Resources:
<LinearGradientBrush x:Key="spOverStateBrush" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#2C8CBF" Offset="0" />
<GradientStop Color="#2793BF" Offset="0.5" />
<GradientStop Color="#2483BF" Offset="0.5001" />
<GradientStop Color="#2C8CBF" Offset="1" />
</LinearGradientBrush>
<LinearGradientBrush x:Key="spPressedStateBrush" StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#0C6C9F" Offset="0" />
<GradientStop Color="#07739F" Offset="0.5" />
<GradientStop Color="#04639F" Offset="0.5001" />
<GradientStop Color="#0C6C9F" Offset="1" />
</LinearGradientBrush>
So I'm pretty sure those dynamic resources are the culprit, but how would I solve this problem?
Be sure that both this two (
spOverStateBrush
orspPressedStateBrush
) Brushes are not used in different place in your code.In order to be animatable, the Background Brush (
spOverStateBrush
orspPressedStateBrush
) of theBorder
must be mutable, which the default value isn't.If you use one of these two Brushes in another place, You should assign a new LinearGradientBrush before animating something like this code:
After painstakingly trying to debug it by comparing the code to the original Control Template, I figured out that transporting all of the resources that my control uses into the file itself, and replacing all
DynamicResources
withStaticResources
and that fixed the bug I was having.