2015-04-01 46 views
0

我希望我的WPF窗口的背景在特定情況下更改(但也可以是任何其他屬性)。假設窗口的名稱是myWindow1。如果我像對待任何其他項目一樣對待窗口(就像在Windows窗體中那樣),myWindow1似乎沒有要設置的Background屬性;自動完成中只顯示只讀屬性。如果我嘗試創建一個像這樣的新對象: myWindow1 w1 = new myWindow1(); 然後w1似乎具有更改自動完成(包括背景)的所有正確屬性,並且IDE不顯示任何錯誤。但是當我嘗試啓動程序時,它會掛起。在代碼隱藏(WPF)中更改Visual C#中的窗口屬性

我在做什麼錯,什麼是從Visual C#2013中的代碼隱藏更改WPF窗口屬性的最佳做法?

+0

確定myWindow1是窗口的一個實例。它應該有一個背景屬性。你也不能寫新的myWindow1() – 2015-04-01 17:52:12

+0

如何在創建實例時使用MyWindow1方法? – user2526236 2015-04-01 17:54:07

回答

1

嘗試從XAML執行此操作。

< Window x:Class="WPF1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525" > 
<Grid Background="{DynamicResource {x:Static SystemColors.InactiveCaptionTextBrushKey}}"> 

</Grid> 

這也是動態資源

<Window x:Class="WPF1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Background="{DynamicResource WindowBrush}" 
    Title="MainWindow" Height="350" Width="525" > 
<Window.Resources> 
<SolidColorBrush x:Key="WindowBrush" Color="LightGray"/> 
</Window.Resources> 
<Grid > 
    </Grid> 
</Window> 

它也可以與靜態資源

1
  1. 做你不應該建立在同一窗口的新實例。因爲它會覆蓋您嘗試啓動的那個。
    2.To達到自己的目標,我可能會使用一個奇特的動畫是這樣的:

    function changeBGColor(this migth be an event handler) 
    { 
         Storyboard sb=new storyboard(); 
         ColorAnimation ca=new ColorAnimation(); 
         ca.From = Colors.Teal; 
         ca.By = Colors.Green; 
         ca.To = Colors.YellowGreen; 
         ca.Duration = new Duration(TimeSpan.FromSeconds(1.5)); 
         Storyboard.SetTargetProperty(ca, new PropertyPath("(Background.BackgroundBrus).(SolidColorBrush.Color)")); 
         myWindow1.beginStoryboard(sb); 
    } 
    
+0

我使用了ColorAnimation,但在網格上,就像user2526236建議的那樣,並且實現了我想要的。更改網格的背景屬性就足夠了,但我需要計時並返回到第一個狀態,所以動畫在控制事件流動方面很有用(animation.complete(function))。不過,我想知道是否可以在窗口加載時編輯窗口的屬性,以及如何編輯。 – didrocks66 2015-04-02 16:37:38

+0

是的,你可以。請記住,只要創建它,就有一個mainWindow的實例!你可以做這樣的事情:'this.width = 230;' – Gino 2015-04-02 18:51:41

相關問題