didrocks66
didrocks66

Reputation: 97

Changing window properties in Visual C# from code-behind (WPF)

I want the background of my WPF window to change in a specific situation (but could as well be any other property). Let's suppose the name of the window is myWindow1. If I treat the window just like any other item (like you would do in Windows Forms), myWindow1 doesn't seem to have a Background property to set; only read-only properties are shown in auto-complete. If I try creating a new object like this: myWindow1 w1 = new myWindow1(); then w1 seems to have all the right properties available for changing in autocomplete, including background, and the IDE shows no errors. But when I try starting the program, it hangs.

What am I doing wrong, and what is the best practice for changing WPF windows properties from code-behind in Visual C# 2013?

Upvotes: 0

Views: 1183

Answers (2)

Gino
Gino

Reputation: 176

  1. You shouldn't create a new instance of the same windows. Because it overrides the one you're trying to launch.
    2.To reach your goal, I would probably use a fancy animation something like:

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

Upvotes: 1

user2526236
user2526236

Reputation: 1538

Try to do this from 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>

this is also dynamic resource

<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>

It also be done with static resource

Upvotes: 1

Related Questions