2

我花了一整天的时间试图弄清楚为什么这个用户控件会导致 VS2010(Windows Phone 7.1 开发)崩溃。应用程序运行此控件没有问题,但是当我在 MainPage.xaml 中进入设计模式时 - VS 崩溃。

<UserControl x:Class="blabla.Controls.Tile"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}">

    <UserControl.Resources>
        <Storyboard x:Name="SwitchSidesAnimation">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationX)" Storyboard.TargetName="FrontSide">
                <EasingDoubleKeyFrame KeyTime="0" Value="0"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="90"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause1" KeyTime="0:0:6" Value="-90"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause2" KeyTime="0:0:6.2" Value="-90"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause3" KeyTime="0:0:6.4" Value="0"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause4" KeyTime="0:0:12" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Projection).(PlaneProjection.RotationX)" Storyboard.TargetName="BackSide">
                <EasingDoubleKeyFrame KeyTime="0" Value="-90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="-90"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="0"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause5" KeyTime="0:0:6" Value="0"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause6" KeyTime="0:0:6.2" Value="90"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause7" KeyTime="0:0:6.4" Value="90"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause8" KeyTime="0:0:12" Value="90"/>
            </DoubleAnimationUsingKeyFrames>
            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="FrontSide">
                <DiscreteObjectKeyFrame KeyTime="0:0:0.2">
                    <DiscreteObjectKeyFrame.Value>
                        <Visibility>Visible</Visibility>
                    </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
                <DiscreteObjectKeyFrame KeyTime="0:0:0.4">
                    <DiscreteObjectKeyFrame.Value>
                        <Visibility>Collapsed</Visibility>
                    </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
                <DiscreteObjectKeyFrame x:Name="MoveThisForPause9" KeyTime="0:0:6">
                    <DiscreteObjectKeyFrame.Value>
                        <Visibility>Visible</Visibility>
                    </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
                <DiscreteObjectKeyFrame x:Name="MoveThisForPause10" KeyTime="0:0:6.4">
                    <DiscreteObjectKeyFrame.Value>
                        <Visibility>Visible</Visibility>
                    </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
                <DiscreteObjectKeyFrame x:Name="MoveThisForPause11" KeyTime="0:0:12">
                    <DiscreteObjectKeyFrame.Value>
                        <Visibility>Visible</Visibility>
                    </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
            </ObjectAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)" Storyboard.TargetName="FrontSide">
                <EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="0"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause12" KeyTime="0:0:6" Value="0"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause13" KeyTime="0:0:6.2" Value="0"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause14" KeyTime="0:0:6.4" Value="0"/>
                <EasingDoubleKeyFrame x:Name="MoveThisForPause15" KeyTime="0:0:12" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>

        <!-- Front side -->
        <Grid x:Name="FrontSide" Grid.Column="0" Grid.Row="0"
              Background="{Binding FrontBackground}">
            <Image Source="{Binding FrontImage}" />
        </Grid>
        <!-- /Front side -->

        <!-- Back side -->
        <Grid x:Name="BackSide" Grid.Column="0" Grid.Row="0"
              Background="{Binding BackBackground}">
            <Grid.Projection>
                <PlaneProjection RotationX="-90" />
            </Grid.Projection>
            <Image Source="{Binding BackImage}" />
        </Grid>
        <!-- /Back side -->
    </Grid>
</UserControl>

现在是代码。

namespace blabla.Controls
{
    public partial class Tile : UserControl
    {
        /// <summary>
        /// Defines if the tile has two sides.
        /// </summary>
        public bool IsTwoSided
        {
            get { return (bool)GetValue(IsTwoSidedProperty); }
            set
            {
                SetValue(IsTwoSidedProperty, value);

                this.startAnimations();
            }
        }

        /// <summary>
        /// Image that will be displayed on front side.
        /// </summary>
        public BitmapImage FrontImage
        {
            get { return (BitmapImage)GetValue(FrontImageProperty); }
            set { SetValue(FrontImageProperty, value); }
        }

        /// <summary>
        /// Image that ill be displayed on back side.
        /// </summary>
        public BitmapImage BackImage
        {
            get { return (BitmapImage)GetValue(BackImageProperty); }
            set { SetValue(BackImageProperty, value); }
        }

        /// <summary>
        /// Brush that will be used as background for front side.
        /// </summary>
        public Brush FrontBackground
        {
            get { return (Brush)GetValue(FrontBackgroundProperty); }
            set { SetValue(FrontBackgroundProperty, value); }
        }

        /// <summary>
        /// Brush that will be used as background for back side.
        /// </summary>
        public Brush BackBackground
        {
            get { return (Brush)GetValue(BackBackgroundProperty); }
            set { SetValue(BackBackgroundProperty, value); }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////

        public static readonly DependencyProperty IsTwoSidedProperty =
            DependencyProperty.Register("IsTwoSided", typeof(bool), typeof(Tile), new PropertyMetadata(false));

        public static readonly DependencyProperty FrontImageProperty =
            DependencyProperty.Register("FrontImage", typeof(BitmapImage), typeof(Tile), new PropertyMetadata(null));

        public static readonly DependencyProperty BackImageProperty =
            DependencyProperty.Register("BackImage", typeof(BitmapImage), typeof(Tile), new PropertyMetadata(null));

        public static readonly DependencyProperty FrontBackgroundProperty =
            DependencyProperty.Register("FrontBackground", typeof(Brush), typeof(Tile),
            new PropertyMetadata(new SolidColorBrush((Color)Application.Current.Resources["PhoneAccentColor"])));

        public static readonly DependencyProperty BackBackgroundProperty =
            DependencyProperty.Register("BackBackground", typeof(Brush), typeof(Tile),
            new PropertyMetadata(new SolidColorBrush((Color)Application.Current.Resources["PhoneAccentColor"])));

        ///////////////////////////////////////////////////////////////////////////////////////////////////////

        public Tile()
        {
            InitializeComponent();
            this.LayoutRoot.DataContext = this;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Modifies animation frames' KeyTime to adjust time for new timing.
        /// <param name="pauseTime">Lenght of the pause.</param>
        /// </summary>
        private void setPauses(TimeSpan pauseTime)
        {
            // Sets pauses.
            EasingDoubleKeyFrame frameToModify;

            for(int i = 0; true; i++)
            {
                if(this.FindName("MoveThisForPause" + i) != null)
                {
                    frameToModify = (EasingDoubleKeyFrame)this.FindName("MoveThisForPause" + i);
                    frameToModify.KeyTime = KeyTime.FromTimeSpan(frameToModify.KeyTime.TimeSpan - TimeSpan.FromSeconds(5) + pauseTime);
                }
                else
                {
                    break;
                }
            }
        }

        /// <summary>
        /// Starts animations.
        /// </summary>
        /// <param name="beginTime">Usually delay before first-time animation.</param>
        private void startAnimations()
        {
            // We start animations only if the tile is two sided.
            if(this.IsTwoSided)
            {
                // Stopping previous animation.
                this.SwitchSidesAnimation.Stop();

                // Sets correct pauses.
                this.setPauses(TimeSpan.FromSeconds(new Random().Next(5, 10)));

                // Starts animation.
                this.SwitchSidesAnimation.BeginTime = TimeSpan.FromSeconds(new Random().Next(2, 15));
                this.SwitchSidesAnimation.RepeatBehavior = RepeatBehavior.Forever;
                this.SwitchSidesAnimation.Begin();
            }
            else
            {
                this.SwitchSidesAnimation.Stop();
            }
        }
    }
}
4

2 回答 2

4

我已经能够重现这个崩溃,诚然使用非手机版本的 Silverlight,以及在 Visual Web Dev Express 中而不是完整版本的 VS。

问题最终归结为这两个依赖属性声明中指定的默认值:

    public static readonly DependencyProperty FrontBackgroundProperty =
        DependencyProperty.Register("FrontBackground", typeof(Brush), typeof(Tile),
        new PropertyMetadata(new SolidColorBrush((Color)Application.Current.Resources["PhoneAccentColor"])));

    public static readonly DependencyProperty BackBackgroundProperty =
        DependencyProperty.Register("BackBackground", typeof(Brush), typeof(Tile),
        new PropertyMetadata(new SolidColorBrush((Color)Application.Current.Resources["PhoneAccentColor"])));

在我将默认值替换为null(使用 Notepad++ 因为 Visual Web Dev Express 正在崩溃)、删除项目binobj文件夹并重新启动 Visual Web Dev Express 后,崩溃就消失了。当我重新启动 VWDX 时,它抱怨找不到 type Tile,但那是因为我删除了binandobj文件夹。重建解决了这个问题。

我只能猜测到底是什么问题。在Tile类被静态初始化的时候,Application.Current可能是nullApplication.Current.Resources可能是null,或者Application.Current.Resources["PhoneAccentColor"]可能是null(这会导致强制Color转换失败,就像Colora一样struct)。也许 VS 设计器不能很好地处理类型静态初始化期间抛出的异常?

顺便说一句,我还想指出另外几个潜在的问题。首先,这是您的IsTwoSided财产:

    /// <summary>
    /// Defines if the tile has two sides.
    /// </summary>
    public bool IsTwoSided
    {
        get { return (bool)GetValue(IsTwoSidedProperty); }
        set
        {
            SetValue(IsTwoSidedProperty, value);

            this.startAnimations();
        }
    }

看起来您希望在依赖属性更改startAnimations时调用该方法。IsTwoSided您上面编写的代码将无法实现这一点。

当 Silverlight 更改依赖项属性的值时,它不会调用您的属性设置器来执行此操作。如果您希望在依赖属性的值更改时发生某些事情,请改用属性更改回调

其次,在 in 中Tile.xaml,您将Storyboardin声明<UserControl.Resources>如下:

    <Storyboard x:Name="SwitchSidesAnimation">

我建议使用x:Key而不是x:Name,原因有两个:

  • 资源字典中的所有项目(隐式样式除外)都必须有一个x:Key或一个x:Name来标识它们。VS 支持使用x:Name代替x:Key,但这仅作为遗留支持机制存在。

  • 在用户控件 XAML 中的元素中使用x:Name会导致 VSInitializeComponent()在类的自动生成部分Tile(在Tile.g.csobj\Debug 中的某处)中创建一个具有该名称的字段。然而,仅仅因为你可以坚持x:Name一个元素并不一定意味着你将能够访问生成字段中的相应对象。因为SwitchSidesAnimation在您的Tile.xaml(故事板不是 UIElements)中没有命名 UIElement,所以该SwitchSidesAnimation字段将始终为null.

    实际上,x:Key 属性的 MSDN 文档(也链接到上面)提到

    使用键值的 FindName 调用不会检索键控资源

    FindName是用于按名称查找控件的方法。如果您查看,Tile.g.cs您会看到它在那里使用。)

我建议始终x:Key在资源字典中使用,这样您就不会相信您可以直接在代码隐藏中访问此 Storyboard。

要在代码隐藏中访问情节提要,请使用

    this.Resources["SwitchSidesAnimation"] as Storyboard

实际上,如果添加以下属性,则不必更改startAnimations方法:

    private Storyboard SwitchSidesAnimation
    {
        get { return this.Resources["SwitchSidesAnimation"] as Storyboard; }
    }
于 2012-08-05T09:10:56.137 回答
0

我遇到了类似的问题(在开发 Silverlight 5 时),我花了将近 3 天的时间来挣扎,而且肯定会花费更多时间,但幸运的是我在这里找到了解决方案(作者 Luke Woodward)。

就我而言,我使用的是:

    public static readonly DependencyProperty MyStyleProperty = 
        DependencyProperty.Register(
            "MyStyle",
            typeof(Style), 
            typeof(MainButton), 
            new PropertyMetadata(
                    // using this construct as a default value 
                    // makes VS 2010 SP1 to crush!
                    Application.Current.Resources["SomeStyle"] as Style, 
                    OnPropertyChanged
            )
        );

所以这两个问题的共同点是使用一些资源值作为 DependencyProperty 的默认值。

但更悲剧的是,这个问题是在我申请了VS 2010的SP1之后才出现的(因为我想在Silverlight 5中开发,这需要VS 2010的SP1)。

这让我很头疼,也花了很多时间去搜索。

幸好现在已经解决了,谢谢!

于 2012-08-29T17:57:12.873 回答