如何在wpf c#中传递参数

本文关键字:参数 wpf | 更新日期: 2023-09-27 17:50:07

我在WindowAfterLogin.xaml中有一个代码:

<TextBlock x:Name="In_Time" Foreground="#FF55534F" 
           FontSize="71.312" FontFamily="HelveticaNeueCyr" 
           Height="79.45" LineStackingStrategy="BlockLineHeight" 
           Canvas.Left="2.724" LineHeight="71.312" 
           TextAlignment="Center" TextWrapping="Wrap" 
           Canvas.Top="69.985" Width="231.581" Text="09:00" />

然后我想改变WindowAfterLogin.xaml.csTextBlock的值,所以我这样做了:

MainWindow objMainWindow = new MainWindow();
WindowAfterLogin objAfterLogin = new WindowAfterLogin();                
objMainWindow.Show();
objAfterLogin.In_Time.Text = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();
this.Close();

但是,当我按下F5按钮(编译),它没有改变。问题在哪里?

如何在wpf c#中传递参数

您正在创建一个单独的WindowAfterLogin实例吗?如果您想这样做,您将不得不Show()新实例。试试这个:

    WindowAfterLogin objAfterLogin = new WindowAfterLogin();                
    objAfterLoginShow();
    objAfterLogin.In_Time.Text = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();
    //Close(); //Close any other window that needs to be closed..

如果你想改变当前实例的In_Time.Text,(假设它已经显示或当前可见),你可以在构造函数或初始化WindowAfterLogin的方法中尝试:

In_Time.Text = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();

作为答案的简化,尝试写这样的东西而不是您的代码

MainWindow objMainWindow = new MainWindow();
objMainWindow.Show();
In_Time.Text = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();
this.Close(); //Not sure if You need it. Try to comment this line to be able to notice textblock text changes

我也认为你需要

DateTime.Now.ToString("hh:mm") 

代替

DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString()