从代码隐藏(WPF)更改Visual C#中的窗口属性



我希望WPF窗口的背景在特定情况下发生变化(但也可以是任何其他属性)。假设窗口的名称为myWindow1。如果我像对待任何其他项目一样对待窗口(就像在Windows窗体中一样),myWindow1似乎没有要设置的Background属性;只有只读属性显示在自动完成中。如果我尝试创建这样的新对象:myWindow1 w1 = new myWindow1();那么w1似乎拥有所有可以在自动完成中更改的正确属性,包括后台,并且IDE没有显示任何错误。但当我尝试启动程序时,它挂起了。

我做错了什么,在Visual C#2013中从代码隐藏更改WPF窗口属性的最佳实践是什么?

尝试从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. 您不应该创建相同窗口的新实例。因为它会覆盖您要启动的程序
    2.为了达到你的目标,我可能会用一个花哨的动画,比如:

    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);
    }
    

最新更新