C# 无法转换类型System.Windows.WindowCollection';至';UITestApp.UiSimulator

C# 无法转换类型System.Windows.WindowCollection';至';UITestApp.UiSimulator,c#,wpf,C#,Wpf,我有一个带有几个按钮的wpf窗口,我有另一个类,其中wpf窗口的操作是完成的。保存文件后,我需要从类中禁用WPF窗口的按钮。这导致了错误 错误:无法将System.Windows.WindowCollection类型“”转换为UITestApp.UiSimulator类型 对于以下代码 if (result == true) { // Save document SaveParamFile(dlg.FileN

我有一个带有几个按钮的wpf窗口,我有另一个类,其中wpf窗口的操作是完成的。保存文件后,我需要从类中禁用WPF窗口的按钮。这导致了错误

错误:无法将System.Windows.WindowCollection类型“”转换为UITestApp.UiSimulator类型

对于以下代码

if (result == true)
            {
                // Save document
                SaveParamFile(dlg.FileName);
                UISimulator uv = (UISimulator)Application.Current.Windows;
                uv.btnSave.IsEnabled = false;
            }

Application.Current.Windows仅包含主UI线程上存在的窗口。在主UI线程之外的任何其他线程上创建窗口都不是一个好的做法

您无法从另一个线程直接访问/操作UI。唯一的解决方案是在线程中引发事件,然后在UI线程中捕获它。UI元素具有非常严格的线程关联性要求。这意味着您只能从承载该元素的线程访问该元素。这包括各种访问,包括简单读取。您可以使用委托来实现这一点。 将下面一行放在需要更新UI的位置。 使用
[Dispatcher.Invoke(DispatcherPriority, 委派)]
从其他线程或后台更改UI

 Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
    //Update UI here
}));

您正在将WindowCollection强制转换为Window,这就是抛出错误的原因,您必须从集合中找到窗口并需要强制转换它。 如果UISimulator是主窗口,您可以这样使用

if (result == true)
            {
                // Save document
                SaveParamFile(dlg.FileName);
                UISimulator uv = (UISimulator)Application.Current.MainWindow;
                uv.btnSave.IsEnabled = false;
            }
或者你必须找到下面的窗口

if (result == true)
        {
            // Save document
            SaveParamFile(dlg.FileName);
            UISimulator uv = (UISimulator)Application.Current.Windows.OfType<UISimulator>().FirstOrDefault();
            uv.btnSave.IsEnabled = false;
        }
if(结果==true)
{
//保存文档
SaveParamFile(dlg.FileName);
UISimulator uv=(UISimulator)Application.Current.Windows.OfType().FirstOrDefault();
uv.btnSave.IsEnabled=false;
}

那么我如何访问/操作主UI控件的功能。我是wpf的初学者