2012-03-04 4 views
0

나는 프로젝트에서 작업 중이므로 일반 class.cs에서 레이블에 액세스해야합니다.
MainWindow.xaml.cs에서 가져온 것이 아닙니다!일반 클래스 (.cs)에서 액세스 제어

MainWindow.xaml : 레이블 lblTag을 포함합니다.

lblTag.Content = "Content"; 

내가 그것을 어떻게 실현할 수 :

Class.cs 실행할 필요가 있겠습니까?

결국 나는 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 : 당신은 당신의 클래스에서 MainWindow를 클래스의 인스턴스에 대한 참조를 필요

[...] 
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

Class.cs

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

'

+0

은 lblTag.Content = "String"이 아닙니다; 충분하다? – Bahamut

+0

컨트롤이 * named * lblTag 인 경우 "lblTag.Content"(따옴표 제외)를 사용할 수 있어야합니다. "this"라고 입력 해보십시오. Intellisense에서 XAML의 컨트롤에 대해 알려주는 내용을 확인하십시오. – kaj

답변

1

:

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 :

+0

방금 ​​추가하면 window.lbl에서 NullReferenceException이 발생합니다 .. – dr0n3

+0

@ dr0n3 : 아마도 윈도우 변수를 설정하지 않았기 때문일 수 있습니다. – Robar

+1

@ dr0n3 먼저 변수를 초기화해야합니다. 그에 따라 대답을 편집했습니다. –

0

을 사용해야합니다. Damir의 대답은 정확해야합니다.

메인 윈도우 오브젝트를 Class.cs에 추가하고 메인 윈도우의 인스턴스를 클래스의 생성자에 전달하십시오. 예를 들어, MainWindow.xaml.cs를

컨트롤의 이름을 지정
... 
MainWindow mWindow = null; 

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

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

그냥이 개체가 이미 다른 스레드에서 사용되고 있음을 알리는 InvalidOperationException을 throw합니다. – dr0n3

+0

홀수.메인 윈도우의 레퍼런스를 클래스에 전달하는 방법을 공유 할 수 있습니까? 그리고 당신은 어떻게 클래스 객체를 사용하고 있는가? – Bahamut