Reputation: 39
I have this code. Problem is I need access from class Database
to class MainWindow
. I tried to inherit in Database
from MainWindow
but it didnt work. I just need to have reference in both classes to each other class.
Thanks for any advice!
public partial class MainWindow : Window
{
Database db = new Database(@"database.txt");
public MainWindow()
{
InitializeComponent();
}
public void setLabel(string s)
{
Vystup.Content = s;
}
}
class Database
{
//constructor and other methods
public void doSomething()
{
//Here I want to set Label in MainWindow, something like
//MainWindow.setLabel("hello");
}
}
Upvotes: 0
Views: 502
Reputation: 1659
There are a few ways to do this...
Passing a reference (not recommended)...
public partial class MainWindow : Window {
Database db = new Database(this, @"database.txt");
public void setLabel(string s) {
Vystup.Content = s;
}
}
class Database {
private MainWindow _mainWindow { get; set; }
public Database(MainWindow window, string file) {
this._mainWindow = window;
...
}
public void doSomething() {
_mainWindow.setLabel("hello");
}
}
Database returns value to be set...
public partial class MainWindow : Window {
Database db = new Database(@"database.txt");
public void setLabel(string s) {
Vystup.Content = s;
}
public void SomeDatabaseThing()
{
string returnValue = db.doSomething();
setLabel(returnValue);
}
}
class Database {
public Database(string file) {
...
}
public string doSomething() {
return "hello";
}
}
Passing Action in constructor...
public partial class MainWindow : Window {
Database db = new Database(@"database.txt", setLabel);
public void setLabel(string s) {
Vystup.Content = s;
}
}
class Database {
private Action<string> _onDoSomething = null
public Database(string file, Action<string> onDoSomething) {
this._onDoSomething = onDoSomething;
...
}
public void doSomething() {
onDoSomething("hello");
}
}
Upvotes: 1