[英]c# wpf window opacity change error
I'm working on ac# project with WPF but I've a problem and this makes me crazy :) Here is the problem. 我正在使用WPF进行ac#项目,但是我遇到了问题,这让我发疯了:)这就是问题所在。 I'm trying to change new window's opacity with timer.
我正在尝试使用计时器更改新窗口的不透明度。 But when I run the project, "this.Opacity += .1;"
但是当我运行项目时,“ this.Opacity + = .1;” code throws an exception like "Invalid operation etc..." I'm opening a window from MainWindow.cs file with this code:
代码抛出诸如“无效操作等...”之类的异常,我使用以下代码从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();
}
My ArchiveWindow code is, 我的ArchiveWindow代码是
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");
}
}
}
Can you help me with doing that? 你能帮我吗? Thank you so much!
非常感谢!
Basically, you can't access the timer inside the opacityChange event because it's happening in a different thread. 基本上,您无法访问opacityChange事件内部的计时器,因为它发生在另一个线程中。 You need the Dispatcher to do that.
您需要分派器执行此操作。
Dispatcher.BeginInvoke(new Action(() =>
{
if (this.Opacity == 1)
{
timer1.Stop();
}
else
{
this.Opacity += .1;
}
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.