dr0n3
dr0n3

Reputation: 267

Access controls from a normal class (.cs)

I'm working on a project and need to access a label from a normal class.cs.
NOT from the MainWindow.xaml.cs!

MainWindow.xaml: contains a Label lblTag.

Class.cs needs to execute:

lblTag.Content = "Content";

How can I realize it?

I just end up with 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;
}

[...]

Upvotes: 0

Views: 251

Answers (2)

Damir Arh
Damir Arh

Reputation: 17855

You need a reference to an instance of MainWindow class in your Class:

public Class
{
    private MainWindow window;

    public Class(MainWindow mainWindow)
    {
        window = mainWindow;
    }

    public void MyMethod()
    {
        window.lblTag.Content = "Content";
    }
}

You need to pass a reference to your window instance to the class. From inside your MainWindow window code behind you would call:

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

EDIT:

You can only access controls from the same thread. If your class is running in another thread you need to use the 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;
            }));
}

Upvotes: 1

Bahamut
Bahamut

Reputation: 1939

after the edit, this seems clearer now. Damir's answer should be correct.

Just add a mainwindow object on Class.cs and pass the mainwindow's instance to the class's constructor.

on mainwindow.xaml.cs

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

on Class.cs

...
MainWindow mWindow = null;

// constructor
public Class(MainWindow window)
{
   mWindow = window;
}

private void Initialize()
{
   window.lblTag.Content = "whateverobject";
}

Upvotes: 0

Related Questions