2014-01-26 5 views
0

Сегодня хороший день с тех пор, как я начал с WPF, это для запуска, который я создаю. Используя следующий код, мне удалось получить результат видно на скриншоте:Доступ к элементам элемента управления и анимация по одному

<Grid> 
     <ItemsControl ItemsSource="{Binding Programs}"> 
      <ItemsControl.ItemsPanel> 
       <ItemsPanelTemplate> 
        <WrapPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" /> 
       </ItemsPanelTemplate> 
      </ItemsControl.ItemsPanel> 
      <ItemsControl.ItemTemplate> 
       <DataTemplate> 
        <Button Content="{Binding Text}" Background="Transparent" Foreground="White" Width="128" Height="150" > 
         <Button.RenderTransform> 
          <TransformGroup> 
           <ScaleTransform /> 
          </TransformGroup> 
         </Button.RenderTransform> 
         <Button.Template> 
          <ControlTemplate TargetType="Button"> 
           <Grid> 
            <Grid.RowDefinitions> 
             <RowDefinition Height="*" /> 
             <RowDefinition Height="Auto" /> 
            </Grid.RowDefinitions> 

            <Image Grid.Row="0" Source="{Binding Image}" Height="128" /> 
            <ContentPresenter Grid.Row="1" HorizontalAlignment="Center" Margin="3,10" /> 
            <Rectangle Grid.Row="0" Fill="{TemplateBinding Background}" /> 
            <Rectangle Grid.Row="1" Fill="{TemplateBinding Background}" /> 
           </Grid> 
          </ControlTemplate> 
         </Button.Template> 
         <Button.Resources> 
          <Storyboard SpeedRatio="4" x:Key="MouseEnterStoryboard" x:Name="MouseEnterStoryboard"> 
           <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" To="#22FFFFFF"></ColorAnimation> 
          </Storyboard> 
          <Storyboard SpeedRatio="4" x:Key="MouseLeaveStoryboard" x:Name="MouseLeaveStoryboard"> 
           <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" To="Transparent"></ColorAnimation> 
          </Storyboard> 
          <Storyboard Duration="00:00:00.05" x:Key="MouseClickStoryboard" AutoReverse="True"> 
           <DoubleAnimation To="0.8" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"/> 
           <DoubleAnimation To="0.8" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"/> 
          </Storyboard> 
          <Storyboard x:Key="WindowLoadedStoryboard"> 
           <DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="00:00:01" /> 
          </Storyboard> 
         </Button.Resources> 
         <Button.Triggers> 
          <EventTrigger RoutedEvent="Mouse.MouseEnter"> 
           <BeginStoryboard Storyboard="{StaticResource MouseEnterStoryboard}" /> 
          </EventTrigger> 
          <EventTrigger RoutedEvent="Mouse.MouseLeave"> 
           <BeginStoryboard Storyboard="{StaticResource MouseLeaveStoryboard}" /> 
          </EventTrigger> 
          <EventTrigger RoutedEvent="Button.Click"> 
           <BeginStoryboard Storyboard="{StaticResource MouseClickStoryboard}" /> 
          </EventTrigger> 
          <EventTrigger RoutedEvent="Window.Loaded"> 
           <BeginStoryboard Storyboard="{StaticResource WindowLoadedStoryboard}"></BeginStoryboard> 
          </EventTrigger> 
         </Button.Triggers> 
        </Button> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
     </ItemsControl> 
    </Grid> 

Скриншот:

enter image description here

Теперь для каждого элемента в списке, связанного с этим элементом управления, он создаст кнопку. Как бы я мог получить доступ к этой кнопке программно, еще лучше, как бы я мог обращаться к одной из раскадровки программно, так как присвоение имени (x: им просто не будет делать трюк, который кажется ...

Также, как можно Я аниматирую кнопки один за другим? В настоящее время каждый из них постепенно исчезает в то же время (@ WindowLoadedStoryboard), но я бы хотел, чтобы каждая кнопка замирала один за другим с небольшой задержкой, чтобы создать приятный эффект. достичь этого?

Надежда кто-то может ответить на эти 2 вопроса для меня!

Привет!

+0

Кто-нибудь видел этот вопрос? –

+0

Пожалуйста, не задавайте здесь такие вопросы ... вы можете видеть, что люди * * видели ваш вопрос, просмотрев часть этой страницы (вверху справа), которая показывает статистику просмотра страниц. – Sheridan

ответ

1

Ваша проблема с доступом к элементам, определенным в DataTemplate, вызвана тем, что вы определили эти элементы в DataTemplate ... эти элементы могут отображаться во многих различных типах элементов управления контейнера интерфейса. Решение можно найти на странице How to: Find DataTemplate-Generated Elements из MSDN.

Прежде всего вам необходимо получить соответствующий элемент управления контейнером, который содержит элемент, который имел к нему примененный DataTemplate. Затем вам нужно получить ContentPresenter от этого управления контейнером, а затем вы можете получить DataTemplate от ContentPresenter. Наконец, вы можете получить доступ к именованным элементам из DataTemplate. На странице:

// Getting the currently selected ListBoxItem 
// Note that the ListBox must have 
// IsSynchronizedWithCurrentItem set to True for this to work 
ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator. 
    ContainerFromItem(myListBox.Items.CurrentItem)); 

// Getting the ContentPresenter of myListBoxItem 
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem); 

// Finding textBlock from the DataTemplate that is set on that ContentPresenter 
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate; 
TextBlock myTextBlock = 
    (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter); 

// Do something to the DataTemplate-generated TextBlock 
MessageBox.Show("The text of the TextBlock of the selected list item: " + 
    myTextBlock.Text); 
Смежные вопросы