WPF中如何调用window1到window2的事件

how to call the event of window1 to window 2 in WPF

我有 (Mainwindow) 和 (window1) 在 Mainwindow 我有按钮,在 window1 我有标签。现在我想这样做,以便当我单击主窗口中的按钮时,window1 中的标签颜色会发生变化。 这是 Far 迄今为止尝试过的方法,但没有奏效

public 部分 class 主要Window : Window

{
    public MainWindow()
    {
        InitializeComponent();

      
    }

    private void btnFirstWindow_Click(object sender, RoutedEventArgs e)
    {
        Window1 sWindow = new Window1(btnFirstWindow);
        sWindow.Show();

    }
}

主窗口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 部分 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>

当按钮和标签都在主窗口时,我是这样工作的

public 部分 class 主要Window : 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>

可以在Window2中封装一个函数供Window1调用

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