8

WPFアプリケーションに取り組んでいます。に「Status_label」というラベルがありMainWindow.xamlます。別のクラス(signIn.cs)からコンテンツを変更したいと思います。通常、私はこれを行うことができます

var mainWin = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
mainWin.status_lable.Content = "Irantha signed in";

しかし、私の問題は、signIn.csクラスの別のスレッドを介してアクセスしようとすると、エラーが発生することです。

The calling thread cannot access this object because a different thread owns it.

Dispatcher.Invoke(new Action(() =>{..........または何か他のものを使用してこれを解決できますか?

編集: 私はこのラベル変更アクションを別のクラスからも別のスレッドと呼ぶつもりです

MainWindow.xaml

<Label HorizontalAlignment="Left" Margin="14,312,0,0" Name="status_lable" Width="361"/>

SignIn.cs

    internal void getStudentAttendence()
    {
        Thread captureFingerPrints = new Thread(startCapturing);
        captureFingerPrints.Start();
    }

void mySeparateThreadMethod()
{
    var mainWin = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
    mainWin.status_lable.Dispatcher.Invoke(new Action(()=> mainWin.status_lable.Content ="Irantha signed in"));
}

linevarmainWinリターンエラーThe calling thread cannot access this object because a different thread owns it.

案内してください、

ありがとうございました

4

5 に答える 5

25

質問を解決しました。誰かがこれを必要とすることを願っています。しかし、これが最適化された方法であるかどうかはわかりません。

私のmainWindow.xaml.cs で:

    public  MainWindow()
    {
      main = this;
    }

    internal static MainWindow main;
    internal string Status
    {
        get { return status_lable.Content.ToString(); }
        set { Dispatcher.Invoke(new Action(() => { status_lable.Content = value; })); }
    }

私のSignIn.csクラスから

 MainWindow.main.Status = "Irantha has signed in successfully";

これは私にとってはうまくいきます。ここから詳細を見つけることができます.Change WPF window label content from another class and separate thread

乾杯!!

于 2013-03-28T06:40:06.063 に答える
2

以下のスニペットを試してください:

status_lable.Dispatcher.Invoke(...)
于 2013-03-15T07:14:17.393 に答える
2

答えのおかげで、彼らは私を正しい方向に導いてくれました。私はこの簡単な解決策で終わった:

public partial class MainWindow : Window
{
    public static MainWindow main;

    public MainWindow()
    {
        InitializeComponent();                        
        main = this;
    }
}

次に、別のスレッドで実行される別のクラスのイベントハンドラーで:

internal static void pipeServer_MessageReceived(object sender, MessageReceivedEventArgs e)
    {
        MainWindow.main.Dispatcher.Invoke(new Action(delegate()
        {
            MainWindow.main.WindowState = WindowState.Normal;
        }));
    }

これは、namedPipeline 経由で i メッセージを受信したときに最小化されたウィンドウを表示するためのものです。

于 2015-08-07T09:07:49.943 に答える