C#WPF在第二个cs代码文件的窗口上更新标签

时间:2011-01-28 15:34:37

标签: c# wpf

新手在这里为这个愚蠢的问题感到遗憾,但出于某种原因,我对这个简单的小问题感到很不满意。我在WPF窗口上有一个标签和文本块,我正在尝试从第二个cs代码文件更新它们。我已经尝试了下面的代码,但标签没有得到更新...任何帮助或指导非常感谢!

  • 820File.cs

    MainWindow main = new MainWindow();
    string status820Text = "Now importing blah";
    string status820Label = "Now importing blah";
    main.Update820Status(ref status820Text, ref status820Label);
    
  • MainWindow.cs

    public void Update820Status(ref string status820Text, ref string status820Label)
    {
        this.StatusLabel.Content =status820Label;
        this.StatusTextBlock.Text = status820Text;
    }
    

...它运行但Label和TextBlock没有得到更新,或者没有显示传递的文本。

感谢。

3 个答案:

答案 0 :(得分:2)

当您编写main = new MainWindow()时,您正在创建一个与屏幕上现有窗口无关的全新MainWindow实例。

您需要传递现有的MainWindow实例。

答案 1 :(得分:0)

这可以在WinForms中运行 - 而不是在WPF窗口中。

尝试添加参数。然后在新窗口关闭后读取它(或添加一个事件处理程序立即更新)。

820File.cs

MyWindow w = new MyWindow();
w.MyProperty = "Now importing blah"; // Here we set the initial text
w.ShowDialog(); // Show a modal dialog so this class waits for the changed text
string changedText = w.MyProperty; // Here we read the changed text

mywindow的

public partial class Mywindow : Window
{
    public string MyProperty { get; set; }

    public MyWindow()
    {
    }
    private void btnOk_Click(object sender, RoutedEventArgs e)
    {
        MyProperty = "Some new text"; // Set the text to something new
        this.Close();
    }
}

答案 2 :(得分:0)

以下代码适用于WPF

窗口中的

axml:

 <Label x:Name="lblStatus" Foreground="Red" Content=""/>

您网页背后的代码:

private void Button_Click(object sender, RoutedEventArgs e)
{
   Label lbl = (Label)Application.Current.MainWindow.FindName("lblStatus");
   lbl.Content = "New text";
}