C# 当app.xaml中未定义样式时,是否可以在代码中设置样式

C# 当app.xaml中未定义样式时,是否可以在代码中设置样式,c#,wpf,xaml,C#,Wpf,Xaml,我有定义“MyStyle”的myWindow.xaml- 我无法更改otherWindow的xaml,只能从代码访问它。 我也无法将样式定义移动到app.xaml 我找到了一个,样式是在app.xaml中定义的,可以这样做- Style style = Application.Current.Resources["myStyle"] as Style; otherWindow.Style = style; 但是,由于app.xaml中没有定义我的样式,因此上面的调用不起作用(抛出notFoun

我有定义“MyStyle”的myWindow.xaml-

我无法更改otherWindow的xaml,只能从代码访问它。 我也无法将样式定义移动到app.xaml

我找到了一个,样式是在app.xaml中定义的,可以这样做-

Style style = Application.Current.Resources["myStyle"] as Style;
otherWindow.Style = style;
但是,由于app.xaml中没有定义我的样式,因此上面的调用不起作用(抛出notFound异常)


如何将MyStyle设置为另一个窗口的样式?

MyStyle
当然应该在
App.xaml
中全局定义,如果您打算从
myWindow.xaml
以外的任何其他窗口使用if

如果由于某种原因无法移动样式,则需要为要创建的样式创建一个实例
myWindow
。然后,您可以从那里访问它:

myWindow win = new myWindow();
var style = win.Resources["MyStyle"] as Style;
otherWindow.Style = style;

虽然mm8的答案是正确的,并且非常有帮助,但我仍然想谈谈我最终是如何解决这个问题的:

Style style = Application.Current.MainWindow.Resources["MyStyle"] as Style;
otherWindow.Style = style;
主要的变化是使用“MainWindow”属性,该属性包含包含MyStyle的窗口的实例作为资源(谢谢mm8)


有了这个小小的改变,“MyStyle”现在可以访问了。

你不能从MyWindow的资源中获取样式吗?@Clemens-我该如何通过编程实现呢?如果你有一个MyWindow的实例,通过
window.Resources
@Clemens-没有它的实例,它只定义了应用程序中其他窗口使用的样式,然后,您应该将样式声明从MyWindow.xaml移动到App.xaml。是的,假设MyWindow实际上是您的主窗口,这也可以工作。@mm8-在我的情况下是-非常感谢您的帮助!
myWindow win = new myWindow();
var style = win.Resources["MyStyle"] as Style;
otherWindow.Style = style;
Style style = Application.Current.MainWindow.Resources["MyStyle"] as Style;
otherWindow.Style = style;