2014-01-28 2 views
1

Я все еще участвую в WPF, и мне нужна небольшая помощь, надеюсь, что кто-то сможет мне помочь. Итак, мой вопрос, есть ли способ сделать в wpf некоторый кадр, который автоматически изменит 3 изображения? Так, например, когда я запускаю приложение, он показывает 1 изображение, затем через 2 секунды он меняется на другой и так далее?Изменить изображения в поле

Хорошо, так я добавил так: XAML код: <Image x:Name="slider" Stretch="Fill" Source="Slider/slide1.png"/>

и Сз:

private void MainForm_Loaded(object sender, RoutedEventArgs e) 
     { 
      var dispatcherTimer = new DispatcherTimer(); 
      dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); 
      dispatcherTimer.Interval = new TimeSpan(0, 0, 1); 
      dispatcherTimer.Start(); 
     } 

    private void dispatcherTimer_Tick(object sender, EventArgs e) 
    { 


    } 

Теперь, как сделать это изменение ползунков на клеща?

+1

http://stackoverflow.com/questions/9226514/change-image-after-each-10seconds-in-wpf-image-box –

+0

Обновленный главный пост – Infinitier

ответ

0

Вы можете непосредственно живой источник собственности от XAML сам проверить код ниже

<Grid Height="200" Width="200"> 
     <Grid.Triggers> 
      <EventTrigger RoutedEvent="Loaded"> 
       <BeginStoryboard > 
        <Storyboard > 
         <ObjectAnimationUsingKeyFrames Duration="00:00:06" RepeatBehavior="Forever" Storyboard.TargetName="img1" Storyboard.TargetProperty="(Image.Source)"> 
          <DiscreteObjectKeyFrame KeyTime="00:00:00"> 
           <DiscreteObjectKeyFrame.Value> 
            <BitmapImage UriSource="image1.png" /> 
           </DiscreteObjectKeyFrame.Value> 
          </DiscreteObjectKeyFrame> 
          <DiscreteObjectKeyFrame KeyTime="00:00:02"> 
           <DiscreteObjectKeyFrame.Value> 
            <BitmapImage UriSource="image2.png" /> 
           </DiscreteObjectKeyFrame.Value> 
          </DiscreteObjectKeyFrame> 
          <DiscreteObjectKeyFrame KeyTime="00:00:04"> 
           <DiscreteObjectKeyFrame.Value> 
            <BitmapImage UriSource="image3.png" /> 
           </DiscreteObjectKeyFrame.Value> 
          </DiscreteObjectKeyFrame> 
         </ObjectAnimationUsingKeyFrames> 
        </Storyboard> 
       </BeginStoryboard> 
      </EventTrigger> 
     </Grid.Triggers> 
     <Image x:Name="img1" Stretch="Fill"></Image> 
    </Grid> 

Update

я не думаю, что вы можете анимировать источник изображения с раскадровки, так что вы должны принять 3 изображения и анимировать там свойство видимости

Для загрузки изображений асинхронно вы должны привязываться, для привязки вы можете создать свойство, иначе вы можете пройти путь изображения через параметр преобразователя

<Grid Height="200" Width="200"> 
     <Grid.Triggers> 
      <EventTrigger RoutedEvent="Loaded"> 
       <BeginStoryboard > 
        <Storyboard Duration="00:00:06" RepeatBehavior="Forever" > 
         <ObjectAnimationUsingKeyFrames Duration="00:00:03" Storyboard.TargetName="img1" Storyboard.TargetProperty="Visibility"> 
          <DiscreteObjectKeyFrame KeyTime="00:00:00" Value="{x:Static Visibility.Visible}"/> 
          <DiscreteObjectKeyFrame KeyTime="00:00:02" Value="{x:Static Visibility.Collapsed}"/> 
         </ObjectAnimationUsingKeyFrames> 
         <ObjectAnimationUsingKeyFrames BeginTime="00:00:02" Storyboard.TargetName="img2" Storyboard.TargetProperty="Visibility"> 
          <DiscreteObjectKeyFrame KeyTime="00:00:00" Value="{x:Static Visibility.Visible}"/> 
          <DiscreteObjectKeyFrame KeyTime="00:00:02" Value="{x:Static Visibility.Collapsed}"/> 
         </ObjectAnimationUsingKeyFrames> 
         <ObjectAnimationUsingKeyFrames BeginTime="00:00:04" Storyboard.TargetName="img3" Storyboard.TargetProperty="Visibility"> 
          <DiscreteObjectKeyFrame KeyTime="00:00:00" Value="{x:Static Visibility.Visible}"/> 
          <DiscreteObjectKeyFrame KeyTime="00:00:02" Value="{x:Static Visibility.Collapsed}"/> 
         </ObjectAnimationUsingKeyFrames> 
        </Storyboard> 
       </BeginStoryboard> 
      </EventTrigger> 
     </Grid.Triggers> 
     <Image x:Name="img1" Visibility="Collapsed" Source="{Binding IsAsync=True, Converter={StaticResource ImgConverter}, ConverterParameter=http://mydomain.com/image3.png}" /> 
     <Image x:Name="img2" Visibility="Collapsed" Source="{Binding IsAsync=True, Converter={StaticResource ImgConverter}, ConverterParameter=http://mydomain.com/image2.png}" /> 
     <Image x:Name="img3" Visibility="Collapsed" Source="{Binding IsAsync=True, Converter={StaticResource ImgConverter}, ConverterParameter=http://mydomain.com/image1.png}" /> 
    </Grid> 

Преобразователь:

public class ImgConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if (parameter != null) 
     { 
      BitmapImage bi = new BitmapImage(); 
      bi.BeginInit(); 
      bi.UriSource = new Uri(parameter.ToString(), UriKind.Absolute); 
      bi.CacheOption = BitmapCacheOption.OnLoad; 
      bi.EndInit(); 
      return bi; 
     } 
      return null; 
    } 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

О, спасибо большое, это намного лучше! Но будет ли это работать, если я положил ''? – Infinitier

+0

обновленный ответ будет работать с веб-изображениями –

+0

Ох Спасибо большое! :) – Infinitier

0
private void dispatcherTimer_Tick(object sender, EventArgs e) 
{ 
    BitmapImage image = new BitmapImage(); 
    image.BeginInit(); 
    image.UriSource = new Uri("pack://application:,,,/YourAppName;component/someimage.png"); 
    image.EndInit(); 

    this.myImage.Source = image; 
} 

Манипулирование элементов WPF непосредственно не является хорошей форме, хотя, чтобы сделать «правильный» WPF вы должны использовать MVVM.

+0

хорошо поэтому я исправил его с делами, если case 1, а затем slider1, если case2 поместил слайдер 2 и тот же для случая 3 :) теперь можно загрузить изображение из URL-адреса не из папки приложения? – Infinitier

+0

Да, Uri также согласится, как описано в [документации MSDN для него] (http://msdn.microsoft.com/en-us/library/system.uri (v = vs.110) .aspx) , –

Смежные вопросы