我正在开发一个项目,需要从普通的class.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;
}
[...]
答案 0 :(得分:1)
您需要在类中引用MainWindow类的实例:
public Class
{
private MainWindow window;
public Class(MainWindow mainWindow)
{
window = mainWindow;
}
public void MyMethod()
{
window.lblTag.Content = "Content";
}
}
您需要将对窗口实例的引用传递给类。从您的MainWindow窗口代码中,您可以调用:
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;
}));
}
答案 1 :(得分:0)
编辑后,现在看起来更清晰了。达米尔的答案应该是正确的。
只需在Class.cs上添加一个mainwindow对象,并将mainwindow的实例传递给类的构造函数。
在mainwindow.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";
}