2012-03-21 38 views
0

我已經有一個超鏈接按鈕,其中我設置了按鈕點擊內容後面的代碼,如果登錄成功,則返回新視圖。我該如何設置視圖模型中的xaml內容

private void OkButtonClick(object sender, RoutedEventArgs e) 
    { 
     LoginOperation loginOp = FLS.Utilities.RIAWebContext.Current.Authentication.Login(
      new LoginParameters(usernameTextBox.Text, passwordTextBox.Text)); 
     loginOp.Completed += (s2, e2) => 
     { 
      if (loginOp.HasError) 
      { 
       errorTextBlock.Text = loginOp.Error.Message; 
       loginOp.MarkErrorAsHandled(); 
       return; 
      } 
      else if (!loginOp.LoginSuccess) 
      { 
       errorTextBlock.Text = "Login failed."; 
       return; 
      } 
      else 
      { 
       errorTextBlock.Text = string.Empty; 
       Content = new WelcomeView(); 

      } 
     }; 
    } 

我現在已經將MVVM的代碼移到視圖模型中,並在超鏈接按鈕上使用了delegateCommand。

<UserControl ... > 
<Grid ... > 
... 
<HyperlinkButton Content="Login" Height="23" HorizontalAlignment="Left" Margin="313,265,0,0" Name="loginButton" Command="{Binding Path=LoginCommand}" VerticalAlignment="Top" Width="75"/> 
... 
</Grid> 
</UserControl> 

但我不知道,我怎麼做內容=新WelcomeView();從viewmodel後面的代碼?

回答

0

一個好的設計模式應該是擁有兩個不同的數據模板,一個用於在登錄前呈現數據,另一個用於登錄後使用的第二個數據模板。

有幾種方法可以實現這一點。我通常使用的只是將ViewModel(直接使用綁定)放在Window的唯一子節點上。

在你的ViewModel中實現一個內容選擇器類。這是從DataTemplateSelector派生的類,並使用FindResource API來獲取適當的數據模板。

<Window ...> 
    <Window.Resources> 
     <DataTemplate x:key="beforeLogin"> 
      ... 
     </DataTemplate> 
     <DataTemplate x:Key="afterLogin"> 
      ... 
     </DataTemplate>    
    </Window.Resources> 

    <Window.ContentTemplateSelector> 
     <code:MyTemplateSelector /> 
    </Window.ContentTemplateSelector> 

    <-- Here is the content of Window. It's the view model (data). The View will be 
     bind by the TemplateSelector 
    <code:YourViewModel /> 

</Window> 

查看本頁面:http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.contenttemplateselector.aspx查看相關示例。

還有其他的設計模式。另一個常見的習慣用法是簡單地發射一個「UiRequest」事件,該事件將被視圖的代碼隱藏起來。請記住,MVVM規定ViewModel是「視圖不可知的」,但它並不意味着「沒有代碼隱藏」。這意味着VM不能在視圖中引用任何內容。通過這種方式發生視圖事件(例如數據綁定只是屬性更改事件的包裝)。因此,在您的View Model中有一個事件UiRequest,並設計一個協議。在View的構造函數中 - 註冊一個處理程序。在處理程序中,更改內容(人們使用此習語主要是爲了啓動一個彈出窗口,但它可以在任何地方使用)。

相關問題