Cannot animate (0).(1) on an immutable object?

2019-08-08 15:24发布

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?

2条回答
Lonely孤独者°
2楼-- · 2019-08-08 15:49

Be sure that both this two (spOverStateBrush or spPressedStateBrush) Brushes are not used in different place in your code.

In order to be animatable, the Background Brush (spOverStateBrush or spPressedStateBrush) of the Border 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:

    LinearGradientBrush gradient = new LinearGradientBrush();
    gradient.StartPoint = new Point( 0.5, 0 );
    gradient.EndPoint = new Point( 0.5, 1 );

    gradient.GradientStops.Add(new GradientStop(Colors.Black, 0));
    gradient.GradientStops.Add(new GradientStop(Color.FromArgb(100,69,87,186), 1));

    Border.Background = gradient;
查看更多
beautiful°
3楼-- · 2019-08-08 15:52

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 with StaticResources and that fixed the bug I was having.

查看更多
登录 后发表回答