2015-09-19 83 views
1

我正在使用Silverlight 5編寫的遺留應用程序,該應用程序包含很多反模式和不良做法。我負責使用SingalR添加實時交互(如通知)。
順便說一句,他們使用WCF RIA Services these與認證進行交互。如何從另一個UserControl訪問UserControl的DataContext?

他們有一個主頁,這個頁面中,我得到用戶的通知,並顯示他們的登錄用戶名:

public partial class MainPage : UserControl 
{ 
    public MainPage() 
    { 
     InitializeComponent(); 
     //... 

    } 
} 

因此,大家可以看到我沒有設置DataContext屬性爲只要用戶登錄,我需要在應用程序用戶登錄後設置的MainPage的DataContext的,所以我必須做的是,在LoginOperation_Completed裏面LoginForm頁:

public partial class LoginForm : StackPanel 
{ 
    private LoginRegistrationWindow parentWindow; 
    private LoginInfo loginInfo = new LoginInfo(); 
    public LoginForm() 
    { 
     InitializeComponent(); 
     //... 
    } 

    private void LoginOperation_Completed(LoginOperation loginOperation) 
    { 

    if (loginOperation.LoginSuccess) 
    { 
      // Here I need to access MainPages's DataContext property and set it with my ViewModel 
    } 
    } 
} 

現在我的問題是,我該怎麼設置MainPage的DataContext屬性裏面另一類(在這種情況下爲LoginFrom)?

我也試圖給出一個ID我的MainPage用戶控制和訪問它像這樣:

mainPage.DataContext = new NotificationItemViewModel(); 

但是,編譯器給了我這個錯誤:

The name 'mainPage' does not exist in the current context

+0

請添加您的XAML – Gromy

+0

[這裏](https://gist.github.com/SirwanAfifi/c329af5029db2a8e3f51)中的XAML的MainPage。 –

回答

2

我終於想通了如何解決我的問題,有一個簡單的方法來實現這一目標,我應該在類中創建的MainPage類的靜態實例到的MainPage的DataContext的是這樣的:

MainPage.Instance.DataContext = new NotificationItemViewModel(); 
0

您需要命名MainPage UserControl將其粘貼在LoginForm XAML中。不在MainPage的定義中。

public partial class MainPage : UserControl 
{ 
    public static MainPage Instance { get; private set; } 
    public MainPage() 
    { 
     InitializeComponent(); 
     Instance = this; 
    } 
} 

現在我可以訪問:

+0

屬性在MainPage中,所以我爲什麼要命名LoginForm? –

+0

不,你不需要命名'LoginForm'。您需要在'LoginForm'的XAML中命名'MainPage'的實例。現在,您只需在'MainPage'的描述中命名'UserControl'。 如果你不明白,給我看你的XAML的'LoginForm',我幫你。 – Gromy

+0

[這裏是](https://gist.github.com/SirwanAfifi/e72acb67af8c2034010f)LoginForm的XAML。你能解釋我該怎麼做? –

相關問題