在非活动选项卡上调用事件以进行控制会导致异常

时间:2017-12-28 07:05:01

标签: wpf user-controls controls

有一个控件有动画DoubleAnimationUsingPath,动画由事件RoutedEvent =“ui:CheckBoxProgressCircle.Check”触发

<EventTrigger RoutedEvent="ui:CheckBoxProgressCircle.Check">
    <EventTrigger.Actions>
        <BeginStoryboard>
            <Storyboard>

                <DoubleAnimationUsingPath Storyboard.TargetName="AnimatedTranslateTransform"
                                            Storyboard.TargetProperty="X"
                                            PathGeometry="{StaticResource CheckAnimationPath}"
                                            Source="X"
                                            Duration="0:0:.1" />

            </Storyboard>
        </BeginStoryboard>
    </EventTrigger.Actions>
</EventTrigger>

在代码中,我注册了事件:

static CheckBoxProgressCircle()
{
    CheckEvent =
        EventManager.RegisterRoutedEvent("Check", RoutingStrategy.Tunnel, typeof(RoutedEventHandler), typeof(CheckBoxProgressCircle));
}

public event RoutedEventHandler Check
{
    add
    {
        AddHandler(CheckEvent, value);
    }
    remove
    {
        RemoveHandler(CheckEvent, value);
    }
}

然后我称之为事件:

var newEventArgs = new RoutedEventArgs(CheckEvent);
RaiseEvent(newEventArgs);

如果控件位于处于活动状态的选项卡上,则一切正常,如果控件位于从未变为活动状态的选项卡上,则会出现错误:

  

''AnimatedTranslateTransform'名称在'System.Windows.Controls.ControlTemplate'的名称范围内找不到。'

我认为这是因为控件没有呈现,因为在非活动选项卡上并且没有AnimatedTranslateTransform,如何强制wpf在选项卡变为活动状态之前呈现此元素?或者,如果我错了,我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

解决方案结果非常简单:您可以调用ApplyTemplate()方法;对于这种控制。 https://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.applytemplate.aspx