Skip to main content
 首页 » 编程设计

c#之如何使标签静态化

2024年02月23日16三少

所以我有一个程序,我在其中告诉用户两个骨架是否匹配,但问题是我需要通过 class 访问 label。我不断收到的错误是

Error1  An object reference is required for the 
non-static field, method, or property  
'WpfApplication1.MainWindow.matchLabel' 

这是我的代码:

static标签

static Label matching 
    { 
        get { return matchLabel; } //errors here 
        set { matchLabel = value; } //and here 
    } 

类

private class Scan 
    { 
        private void Start() 
        { 
            Skeleton skeleton = new Skeleton(); 
 
            if (PersonDetected == true) 
            { 
                int SkeletonID2 = skeleton.TrackingId; 
 
                if (SkeletonID1 == SkeletonID2) 
                { 
                    matching.Content = "Your IDs are Matching!"; 
                } 
 
                else if (SkeletonID2 != SkeletonID1) 
                { 
                    matching.Content = "Your IDs don't Match."; 
                } 
            } 
        } 
 
        private void Stop() 
        { 
            if (PersonDetected == true) 
            { 
                matching.Content = "Scan Aborted"; 
            } 
        } 
    } 

基本上我想知道如何在 wpf static 中制作标签,或者是否有其他方法可以做到这一点。
提前致谢

请您参考如下方法:

我认为您可以使用另一种方法,就像@Daniel 所说的那样,在多线程上使用 UI 元素不是一个好主意。

如果我的理解是正确的,你只是想通知用户你的领域逻辑的结果,我会做的很简单,创建一个事件:

public event Action<string> MyEvent = delegate { };

            if (SkeletonID1 == SkeletonID2) 
            { 
                this.MyEvent("Your IDs are Matching!"); 
            } 
 
            else if (SkeletonID2 != SkeletonID1) 
            { 
                this.MyEvent("Your IDs don't Match."); 
            } 
 
 if (PersonDetected == true) 
            { 
                this.MyEvent("Scan Aborted"); 
            } 

在您的 WPF View 中

this.MydomainComponent.MyEvent += (x) => { this.matchLabel.Content = x; };