Почему свойство Projection равно нулю?

#windows-phone-7

#windows-phone-7

Вопрос:

 <ListBox Name="listBoxButtons"
         Height="700">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border Background="{StaticResource PhoneAccentBrush}"
                    Name="border"
                    Width="432" Height="62"
                    Margin="6" Padding="12,0,0,6">
                <TextBlock Text="{Binding}" 
                           Foreground="#FFFFFF" FontSize="26.667"
                           HorizontalAlignment="Left"
                           VerticalAlignment="Bottom"
                           FontFamily="{StaticResource PhoneFontFamilySemiBold}"/>
                <Border.Projection>
                    <PlaneProjection RotationX="-60"/>
                </Border.Projection>
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
  

Код:

 private void ShowAnim()
{
    IEasingFunction quadraticEase = new QuadraticEase { EasingMode = EasingMode.EaseOut };
    Storyboard _swivelShow = new Storyboard();
    foreach (var item in this.listBoxButtons.Items)
    {
        UIElement container = listBoxButtons.ItemContainerGenerator.ContainerFromItem(item) as UIElement;
        if (container != null)
        {
            Border content = VisualTreeHelper.GetChild(container, 0) as Border;
            if (content != null)
            {
                DoubleAnimationUsingKeyFrames showAnimation = new DoubleAnimationUsingKeyFrames();

                EasingDoubleKeyFrame showKeyFrame1 = new EasingDoubleKeyFrame();
                showKeyFrame1.KeyTime = TimeSpan.FromMilliseconds(0);
                showKeyFrame1.Value = -60;
                showKeyFrame1.EasingFunction = quadraticEase;

                EasingDoubleKeyFrame showKeyFrame2 = new EasingDoubleKeyFrame();
                showKeyFrame2.KeyTime = TimeSpan.FromMilliseconds(85);
                showKeyFrame2.Value = 0;
                showKeyFrame2.EasingFunction = quadraticEase;

                showAnimation.KeyFrames.Add(showKeyFrame1);
                showAnimation.KeyFrames.Add(showKeyFrame2);

                Storyboard.SetTargetProperty(showAnimation, new PropertyPath(PlaneProjection.RotationXProperty));
                Storyboard.SetTarget(showAnimation, content.Projection);

                _swivelShow.Children.Add(showAnimation);
            }
        }
    }
    _swivelShow.Begin();
}
  

Но: Storyboard.SetTarget(showAnimation, content.Projection) выдает исключение. content.Projection Есть null . Как это могло произойти?

Ответ №1:

Вы смотрите не на тот Border элемент. Иерархия контейнера элементов в вашем случае выглядит как Border -> ContentControl -> ContentPresenter -> Border (это ваше). Итак, вам нужно пройти глубже по дочерней иерархии вашего контейнера, чтобы найти нужную границу.

Следующий код выполняет рекурсивный поиск дочерних элементов UIElement и выдает некоторый отладочный вывод, чтобы вы могли видеть, насколько глубоко это происходит. Он остановится, когда найдет элемент управления с именем «граница»:

     private UIElement GetMyBorder(UIElement container)
    {
        if (container is FrameworkElement amp;amp; ((FrameworkElement)container).Name == "border")
            return container;

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(container); i  )
        {
            var child = (FrameworkElement)VisualTreeHelper.GetChild(container, i);
            System.Diagnostics.Debug.WriteLine("Found child "  child.ToString());

            System.Diagnostics.Debug.WriteLine("Going one level deeper...");
            UIElement foundElement = GetMyBorder(child);
            if (foundElement != null)
                return foundElement;
        }
        return null;
    }
  

Чтобы использовать его:

     Border content = (Border)GetMyBorder(container);
  

Комментарии:

1. Рад помочь! И если это решит вашу проблему, вы можете принять это как ответ 🙂

2. привет, ListBox. Элементы содержат 15 элементов, но я получаю только 5 элементов, как это могло произойти?

3. Список генерирует контейнеры не для всех элементов, а только для видимых.

4. Вау! Я знаю . ItemsPanel в ListBox — это VirtualizingStackPanel, я должен изменить VirtualizingStackPanel на StackPanel. Спасибо