I have (Mainwindow) and (window1) in Mainwindow I have button and in window1 I have label. now I want to make it so that when I click the button in mainwindow the label color changes in window1. This is what Far have tried so far but it didn't work
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnFirstWindow_Click(object sender, RoutedEventArgs e)
{
Window1 sWindow = new Window1(btnFirstWindow);
sWindow.Show();
}
}
Mainwindow XAML
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button x:Name="btnFirstWindow" Content="Button" HorizontalAlignment="Left" Height="140" Margin="492,77,0,0" VerticalAlignment="Top" Width="151" Click="btnFirstWindow_Click"/>
</Grid>
public partial class Window1 : Window
{
private Button btnfirstWindow;
public Window1(Button btnfirstWindow)
{
this.btnfirstWindow = btnfirstWindow;
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
btnfirstWindow.Click = btnfirstWindow_Click;
}
void btnfirstWindow_Click(object sender, RoutedEventArgs e)
{
lblShowUser.Background = Brushes.Red;
}
}
** Window1 XAML**
Title="Window1" Height="450" Width="800">
<Grid>
<Label Name="lblShowUser" Content="Label" HorizontalAlignment="Left" Height="119" Margin="321,98,0,0" VerticalAlignment="Top" Width="281"/>
</Grid>
This is how I made it work when both the button and label was on mainwindow
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btn_Click(object sender, RoutedEventArgs e)
{
if (Label.Background == Brushes.Black)
{
Label.Background = new LinearGradientBrush(Colors.Red, Colors.Red, 90);
}
else
{
Label.Background = Brushes.Red;
}
}
}
**XAML**
Title="MainWindow" Height="450" Width="800">
<Grid>
<Label Background="NavajoWhite" Name="Label" Content="Label" FontSize="140" HorizontalAlignment="Left" Height="210" Margin="275,104,0,0" VerticalAlignment="Top" Width="497"/>
<Button Name="btn" Content="Button" HorizontalAlignment="Left" Height="56" Margin="40,43,0,0" VerticalAlignment="Top" Width="377" Click="btn_Click"/>
</Grid>
CodePudding user response:
You can encapsulate a function in Window2 for Window1 to call
MainWindow.xaml.cs
public partial class MainWindow : Window
{
Window1 sWindow = new Window1();
public MainWindow()
{
InitializeComponent();
}
private void btnFirstWindow_Click(object sender, RoutedEventArgs e)
{
sWindow.Show();
}
private void btnChangeBackground_Click(object sender, RoutedEventArgs e)
{
//Mainwindow event pass to window1
sWindow.ChangeForeground();
}
}
Window1.xaml.cs
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
public void ChangeBackground(Color color)
{
//do something here
}
}