2017-06-12 32 views
1

沒有定義樣式我有myWindow.xaml在限定「myStyle的」 -是否有可能設定一個風格的代碼時在App.xaml中

<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中調用上面定義沒有按」工作(拋出未發現異常)。

如何將MyStyle設置爲另一個窗口的樣式?

+1

你不能從MyWindow的資源中獲得樣式嗎? – Clemens

+0

@ Clemens-我該如何編程? – Shtut

+0

如果你有一個MyWindow的實例,按'window.Resources'。 – Clemens

回答

1

MyStyle當然應該在App.xaml全局定義如果您打算使用如果從除myWindow.xaml以外的任何其他窗口。

如果由於某種原因無法移動樣式,則需要爲要創建的樣式創建實例myWindow。然後,您可以從那裏訪問:

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

雖然MM8的答案是正確的,是非常有益的,我還是喜歡我的2分錢小費扔,我怎麼結束瞭解決這個:

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

主要變化是使用''MainWindow'屬性,其中包含MyStyle作爲資源(謝謝你mm8)的窗口的實例

隨着「MyStyle」的小改動現在可以訪問。

+0

是的,這也適用於假設myWindow實際上是您的主窗口。 – mm8

+1

@ mm8 - 在我的情況下是 - 非常感謝您的幫助! – Shtut

相關問題