【发布时间】:2019-08-29 06:04:11
【问题描述】:
是否可以对我通过绑定获得的图片进行动画处理?由于我是 C# 和 WPF 的新手,我正在尝试使用绑定等功能。我希望旧图片淡出(可能是不透明度,但这是绑定的选项吗?)并且新图片淡入。或者更好地处理后面代码中的所有内容,我从文件夹中获取图像并绑定它之后。
<UserControl x:Class="Screensaver.ScreensaverControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Screensaver"
mc:Ignorable="d" DataContext="{Binding RelativeSource={RelativeSource Self}}"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Image Visibility="Visible" Source="{Binding DisplayedImagePath}" Name="Bild" Stretch="Uniform" />
</Grid>
</UserControl>
using System;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
namespace Screensaver
{
/// <summary>
/// Interaction logic for ScreensaverControl.xaml
/// </summary>
public partial class ScreensaverControl : UserControl
{
private Timer _timer;
public ScreensaverControl()
{
InitializeComponent();
this.Loaded += ScreensaverControl_Loaded;
this.Unloaded += ScreensaverControl_Unloaded;
}
private void ScreensaverControl_Loaded(object sender, RoutedEventArgs e)
{
_timer = new Timer(OnTimer, _timer, 10, Timeout.Infinite);
}
private void ScreensaverControl_Unloaded(object sender, RoutedEventArgs e)
{
_timer.Dispose();
_timer = null;
}
private int _index = -1;
private void OnTimer(object state)
{
try
{
var files = Directory.GetFiles(@"C:\Users\mhj\source\repos\Screensaver\Fotos\", "*.png");
if (files.Length > 0)
{
_index++;
if (_index >= files.Length)
_index = 0;
this.Dispatcher.Invoke(() => DisplayedImagePath = files[_index]);
}
}
catch (Exception ex)
{
}
finally
{
if (_timer != null)
_timer.Change(10000, Timeout.Infinite);
}
}
public string DisplayedImagePath
{
get { return (string)GetValue(DisplayedImagePathProperty); }
set { SetValue(DisplayedImagePathProperty, value); }
}
// Using a DependencyProperty as the backing store for DisplayedImagePath. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DisplayedImagePathProperty =
DependencyProperty.Register("DisplayedImagePath", typeof(string), typeof(ScreensaverControl), new PropertyMetadata(null));
}
}
【问题讨论】:
-
您当然可以为 Image 元素的 Opacity 设置动画,但这与 Source 属性的 Binding 无关。要制作实际的混合效果,您还需要将两个 Image 元素放在一起,并为两者的 Opacity 设置动画,一个从 1 到 0,另一个从 0 到 1。
-
但是我只绑定了一张图片,我应该在上面再放一张。我如何设置不透明度,因为我需要淡出效果,最好在后面的代码中做到这一点。可悲的是,我无法在 c# 中使用不透明度。
-
还可以考虑使用 DispatcherTimer 而不是 System.Threading.Timer。它的 Tick 处理程序已经在 UI 线程中运行,因此不需要 Dispatcher.Invoke。
-
那么是否应该有混合效果?
-
您的视图模型中的图像属性是
string类型,这看起来也很奇怪。它应该是ImageSource,与Image 类的Source属性完全相同。