tags:

views:

29

answers:

2

I am new to WPF. I have a window that opens another window. This second window would like to change the opacity of a label in the first window. How can I control this value from another window?

A: 

Do follwing things

1- Add 2 windows in your project and define a lable in the Window1 and name it lblTest

2- Launch a Window2 from Window1

3- In Window2 define a button with content =Change Opacity

4- Handle click event o Button in Window2.

5- Put following code in the Click event handler.

(Application.Current.Windows[0] as Window1).lblTemp.Opacity = 0;

for detaied code

Window1.xaml "

<Window x:Class="NOOFWINDOWS.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <Label Name="lblTemp" Content="Wow!"></Label> <Button Height="25" Click="Button_Click" Content="Launch Another Window"></Button> </Grid> </Window> "

Window1.xaml.cs

  public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Window2 w = new Window2();
        w.Show();
    }
}

Window2.xaml

"

' <Window x:Class="NOOFWINDOWS.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window2" Height="300" Width="300">
<Grid>
    <Button Height="25" Content="Change Opacity" Click="Button_Click"></Button>
</Grid>'

"

Window2.xaml.cs

 public partial class Window2 : Window
{
    public Window2()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        (Application.Current.Windows[0] as Window1).lblTemp.Opacity = 0;
    }
}
saurabh
A: 

I think it is better to use a common class outside and Bind the Opacity to a property.

Use INotifyPropertyChanged for the class so that whenever you update the property, the bound Opacity element for the window automatically been modified.

public class Model :INotifyPropertyChanged
{
  .... Implement interface ... 

  public double Opacity
  {
    get { return this._opacity; } 
    set {this._opacity = value; this.OnPropertyChanged("Opacity"); } 
  }
}

In this way if both of your classes can access the same object of Model, and you bind Opacity of the form with the Opacity property of the Model, it will update the control using INotifyPropertyChanged.

To create an object for which all objects have access, use App.Resources.

abhishek