我正在使用WPF处理一个c#项目,但我遇到了一个问题,这让我:)这就是问题所在。我正在尝试使用计时器更改新窗口的不透明度。但是当我运行该项目时,"这个。不透明度 += .1;" 代码引发异常,例如"无效操作等..."我正在从 MainWindow .cs 文件中打开一个窗口,其中包含以下代码:
private void MenuItemArchiveClick(object sender, RoutedEventArgs e)
{
var archiveWindow = new ArchiveWindow();
var screenSize = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
archiveWindow.Width = (screenSize.Width * 95) / 100;
archiveWindow.Height = (screenSize.Height * 90) / 100;
archiveWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
archiveWindow.Margin = new Thickness(0, 10, 0, 0);
archiveWindow.AllowsTransparency = true;
archiveWindow.Opacity = 0.1;
archiveWindow.Topmost = true;
archiveWindow.Show();
}
我的存档窗口代码是,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace POCentury
{
/// <summary>
/// Interaction logic for ArchiveWindow.xaml
/// </summary>
public partial class ArchiveWindow : Window
{
Timer timer1 = new Timer();
public ArchiveWindow()
{
InitializeComponent();
timer1.Interval = 1 * 1000;
timer1.Elapsed += new ElapsedEventHandler(opacityChange);
timer1.Enabled = true;
timer1.AutoReset = false;
timer1.Start();
}
private void opacityChange(object sender, EventArgs a)
{
if (this.Opacity == 1)
{
timer1.Stop();
}
else
{
this.Opacity += .1;
}
}
private void ArchiveWindowClose()
{
timer1.Stop();
this.Close();
}
private void btnArchiveWindowClose(object sender, RoutedEventArgs e)
{
ArchiveWindowClose();
}
private void imgPatternClick(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("sd");
}
}
}
你能帮我这样做吗?非常感谢!
基本上,您无法访问 opacityChange 事件中的计时器,因为它发生在不同的线程中。您需要调度程序来执行此操作。
Dispatcher.BeginInvoke(new Action(() =>
{
if (this.Opacity == 1)
{
timer1.Stop();
}
else
{
this.Opacity += .1;
}
}));