WPF - 无法更改OnChanged方法(从FileSystemWatcher的发射)内的GUI属性 [英] WPF - Cannot change a GUI property inside the OnChanged method (fired from FileSystemWatcher)
问题描述
我想换一个GUI属性的OnChanged方法......(实际上我尝试设置图像源..但这里使用一个按键为简单起见)。这就是所谓的每次FileSystemWatcher的检测文件的改变..它获取到顶输出..但捕捉时,它会尝试设置按钮的宽度异常。
但如果我把相同的代码在一个按钮..它工作得很好。我真心不明白为什么..有人可以帮我吗?
私人无效调用onChanged(对象源,FileSystemEventArgs E)
{
//防止二次烧成,已知的bug为FileSystemWatcher的
试
{
_jsonWatcher.EnableRaisingEvents = FALSE;
FileInfo的objFileInfo =新的FileInfo(e.FullPath);
如果(objFileInfo.Exists!)回报; //忽略文件打开,等待完整的写
//在这里做的东西
Console.WriteLine(顶);
Test_Button.Width = 500;
Console.WriteLine(底部);
}
赶上(例外)
{
//什么也不做
}
终于
{
_jsonWatcher.EnableRaisingEvents = TRUE ;
}
}
我真正想要做而不是改变一个按钮的宽度:
BlueBan1_Image.Source = GUI.GetChampImageSource(JSONFile.Get(蓝禁止1),阿凡达 );
现在的问题是,本次活动是在后台上调线。您需要名帅回调到UI线程:
//在这里做的东西
Console.WriteLine(最佳);
this.Dispatcher.BeginInvoke(新动作(()=>
{
//这个运行在UI线程
BlueBan1_Image.Source = GUI.GetChampImageSource(JSONFile.Get (蓝禁止1),阿凡达);
Test_Button.Width = 500;
}));
Console.WriteLine(底部);
I want to change a GUI property in the OnChanged method... (in actuality im trying to set an image source.. but used a button here for simplicity). This is called everytime filesystemwatcher detects a change in a file.. and it gets to the "top" output.. but catches an exception when it tries to set the button width.
but if i put the same code in a button.. it works just fine. I sincerely don't understand why.. can someone help me?
private void OnChanged(object source, FileSystemEventArgs e)
{
//prevents a double firing, known bug for filesystemwatcher
try
{
_jsonWatcher.EnableRaisingEvents = false;
FileInfo objFileInfo = new FileInfo(e.FullPath);
if (!objFileInfo.Exists) return; // ignore the file open, wait for complete write
//do stuff here
Console.WriteLine("top");
Test_Button.Width = 500;
Console.WriteLine("bottom");
}
catch (Exception)
{
//do nothing
}
finally
{
_jsonWatcher.EnableRaisingEvents = true;
}
}
what i'm really trying to do instead of changing a button width:
BlueBan1_Image.Source = GUI.GetChampImageSource(JSONFile.Get("blue ban 1"), "avatar");
The problem is that this event is raised on a background thread. You need to marshal the call back to the UI thread:
// do stuff here
Console.WriteLine("top");
this.Dispatcher.BeginInvoke(new Action( () =>
{
// This runs on the UI thread
BlueBan1_Image.Source = GUI.GetChampImageSource(JSONFile.Get("blue ban 1"), "avatar");
Test_Button.Width = 500;
}));
Console.WriteLine("bottom");
这篇关于WPF - 无法更改OnChanged方法(从FileSystemWatcher的发射)内的GUI属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!