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

时间:2017-06-12 11:45:07

标签: c# wpf xaml

我有 myWindow.xaml ,它定义了" MyStyle" -

<ResourceDictionary ...>
    <Style x:Key="MyStyle" TargetType="{x:Type Window}">
        //style definitions etc
    </Style>
</ResourceDictionary>

myWindow.xaml只定义了样式,没有它的实例。

我想设置另一个窗口也使用MyStyle,即

otherWindow.Style = "MyStyle"

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

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

Style style = Application.Current.Resources["myStyle"] as Style;
otherWindow.Style = style;

但是,由于我的样式未在app.xaml中定义,因此上面的调用不起作用(抛出notFound异常)。

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

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

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

Style style = Application.Current.MainWindow.Resources["MyStyle"] as Style;
otherWindow.Style = style;

主要更改是使用“ MainWindow ”属性,该属性包含包含MyStyle的窗口的实例作为资源(谢谢mm8)。

通过这个小改动,'MyStyle'现在可以访问。