2011-01-28 13 views
0

ここで初心者の方はごめんなさい。何らかの理由でこの簡単な小さな問題に本当に問題があります。 WPFウィンドウにラベルとテキストブロックがあり、2番目のコードファイルからそれらを更新しようとしています。私は下のコードを試しましたが、ラベルが更新されていません...任意のヘルプやガイダンスをいただければ幸いです!C#WPF 2nd 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; 
    } 
    

...それが実行されますが、ラベルとのTextBlockが更新され得ていないか、むしろ表示されませんテキストは通過しました。

ありがとうございました。

+0

これはかなりうまく見えますが、問題は別の場所にある可能性があります。 LabelとTextBlockの作成方法を教えてください。 –

+1

あなたは 'ref'パラメータを使うべきではありません。 – SLaks

答えて

2

main = new MainWindow()と書くと、新しいMainWindowインスタンスが作成され、画面上の既存のウィンドウとは何の関係もありません。

既存のMainWindowインスタンスを渡す必要があります。

+0

SLaksが正しいです。あなたのような状況では、 'Application.Current.MainWindow'を試してみることもできます。 –

0

WPFウィンドウではなくWinFormsで動作します。

代わりにパラメータを追加してください。そして、新しいウィンドウが閉じられた後にそれを読んでください(またはすぐに更新するイベントハンドラを追加してください)。

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(); 
    } 
} 
+0

間違っています。彼は間違ったインスタンスを使用しているので、WinFormsとWPFの両方で失敗します。 – SLaks

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"; 
} 
関連する問題