从普通类(.cs)访问控件

本文关键字:访问 控件 cs | 更新日期: 2023-09-27 18:26:41

我正在处理一个项目,需要访问一个普通类.cs中的标签。
不是来自MainWindow.xaml.cs!

MainWindow.xaml:包含一个标签lblTag

Class.cs需要执行:

lblTag.Content = "Content";

我怎么能意识到呢?

我最终得到了InvalidOperationExceptions

Window1.xaml.cs:

public Window1()
{
    InitializeComponent();
    [...]
}
[...]
StreamElement se1;
StreamElement se2;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    [...]
    se1 = new StreamElement(this);
    se2 = new StreamElement(this);
    [...]
}
[...]

StreamElement.cs:

[...]
private Window1 _window;
[...]
public StreamElement(Window1 window)
{
    _window = window;
}
[...]
//metaSync is called, whenever the station (it's a sort of internet radio recorder)
//changes the meta data
public void metaSync(int handle, int channle, int data, IntPtr user)
{
    [...]
    //Tags just gets the meta data from the file stream
    Tags t = new Tags(_url, _stream);
    t.getTags();
    //throws InvalidOperationException - Already used in another thread
    //_window.lblTag.Content = "Content" + t.title;
}
[...]

从普通类(.cs)访问控件

您需要在class:中引用MainWindow类的实例

public Class
{
    private MainWindow window;
    public Class(MainWindow mainWindow)
    {
        window = mainWindow;
    }
    public void MyMethod()
    {
        window.lblTag.Content = "Content";
    }
}

您需要将对窗口实例的引用传递给类。从您的主窗口内,您身后的代码将调用:

var c = new Class(this);
c.MyMethod();

编辑:

您只能从同一个线程访问控件。如果您的类正在另一个线程中运行,则需要使用Dispatcher:

public void metaSync(int handle, int channle, int data, IntPtr user)
{
    [...]
    //Tags just gets the meta data from the file stream
    Tags t = new Tags(_url, _stream);
    t.getTags();
    //throws InvalidOperationException - Already used in another thread
    //_window.lblTag.Content = "Content" + t.title;
    _window.lblTag.Dispatcher.BeginInvoke((Action)(() =>
            {
                _window.lblTag.Content = "Content" + t.title;
            }));
}

编辑后,这一点现在似乎更清楚了。达米尔的答案应该是正确的。

只需在Class.cs上添加一个主窗口对象,并将主窗口的实例传递给类的构造函数。

在主窗口.xaml.cs 上

...
Class class = new Class(this);
...

关于Class.cs

...
MainWindow mWindow = null;
// constructor
public Class(MainWindow window)
{
   mWindow = window;
}
private void Initialize()
{
   window.lblTag.Content = "whateverobject";
}