2015-10-11 4 views
3

Я новичок в телефоне Windows. Я хочу создать приложение, но на самом деле у меня проблема с командой Binding.Windows Phone Mvvm Light Перемещение между видами

Я хочу на щелчок, чтобы изменить вид

В моей странице у меня есть 2 кнопки: Вход/Регистрация в моем MainPage.xaml на View Folder

<phone:PhoneApplicationPage> 

    <Grid> 
     <Grid.Background> 
      <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> 
       <GradientStop Color="Black" Offset="0"/> 
       <GradientStop Color="#FF563AA0" Offset="1"/> 
      </LinearGradientBrush> 
     </Grid.Background> 

     <ContentControl Content="{Binding CurrentViewModel}" /> 

     <Button 
      Command="{Binding ConnexionViewCommand}" 
      x:Name="Connexion_button" 
      HorizontalAlignment="Left" 
      Margin="90,308,0,0" 
      Content="Login" 
      VerticalAlignment="Top" 
      Width="282"/> 
     <Button 
      Command="{Binding InscriptionViewCommand}" 
      x:Name="Create_account" 
      HorizontalAlignment="Left" 
      Margin="90,446,0,0" 
      Content="Create Account" 
      VerticalAlignment="Top" 
      Width="282"/> 
    </Grid> 

</phone:PhoneApplicationPage> 

У меня есть 3 файлов в моем папка Вид: ConnexionView.xaml и InscriptionView.xaml и MainPage.xaml

5 файлов в моей папке ViewModel: ConnexionViewModel.cs, InscriptionViewModel.cs, MainPageViewModel.cs, MainViewModel.cs и ViewModelLocator.cs

Я стараюсь следовать этому примеру, но я не очень понимаю.

http://www.codeproject.com/Articles/323187/MVVMLight-Using-Two-Views

я добавить этот код в моем MainViewModel.cs, но я не знаю, что я должен делать.

namespace TeysserApp.ViewModel 
{ 
    public class MainViewModel : ViewModelBase 
    { 
     private ViewModelBase _currentViewModel; 

     readonly static ConnexionViewModel _ConnexionViewModel = new ConnexionViewModel(); 
     readonly static InscriptionViewModel _InscriptionViewModel = new InscriptionViewModel(); 
     readonly static MainPageViewModel _MainPageViewModel = new MainPageViewModel(); 


     public ViewModelBase CurrentViewModel 
     { 
      get 
      { 
       return _currentViewModel; 
      } 
      set 
      { 
       if (_currentViewModel == value) 
        return; 
       _currentViewModel = value; 
       RaisePropertyChanged("CurrentViewModel"); 
      } 
     } 
     public ICommand ConnexionViewCommand { get; private set; } 
     public ICommand InscriptionViewCommand { get; private set; } 

     public MainViewModel() 
     { 
      CurrentViewModel = MainViewModel._MainPageViewModel; 
      ConnexionViewCommand = new RelayCommand(() => ExecuteCommandViewCommand()); 
      InscriptionViewCommand = new RelayCommand(() => ExecuteInscriptionViewCommand()); 
     } 
     private void ExecuteConnexionViewCommand() 
     { 
      CurrentViewModel = MainViewModel._ConnexionViewModel; 
     } 

     private void ExecuteSecondViewCommand() 
     { 
      CurrentViewModel = MainViewModel._InscriptionViewModel; 
     } 

    } 
} 

Вот мой ViewModelLocator.cs

namespace TestApp.ViewModel 
{ 
    /// <summary> 
    /// This class contains static references to all the view models in the 
    /// application and provides an entry point for the bindings. 
    /// <para> 
    /// See http://www.galasoft.ch/mvvm 
    /// </para> 
    /// </summary> 
    public class ViewModelLocator 
    { 
     static ViewModelLocator() 
     { 
      ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); 

      if (ViewModelBase.IsInDesignModeStatic) 
      { 
       // SimpleIoc.Default.Register<IDataService, Design.DesignDataService>(); 
      } 
      else 
      { 
       // SimpleIoc.Default.Register<IDataService, DataService>(); 
      } 

      SimpleIoc.Default.Register<MainViewModel>(); 
      SimpleIoc.Default.Register<ConnexionViewModel>(); 
      SimpleIoc.Default.Register<InscriptionViewModel>(); 
     } 

     /// <summary> 
     /// Gets the Main property. 
     /// </summary> 
     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", 
      "CA1822:MarkMembersAsStatic", 
      Justification = "This non-static member is needed for data binding purposes.")] 
     public MainViewModel Main 
     { 
      get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } 
     } 
     public ConnexionViewModel ConnexionView 
     { 
      get { return ServiceLocator.Current.GetInstance<ConnexionViewModel>(); } 
     } 
     public InscriptionViewModel InscriptionView 
     { 
      get { return ServiceLocator.Current.GetInstance<InscriptionViewModel>(); } 
     } 
    } 
} 

Вот мои App.xaml

<Application 
    x:Class="TeysserApp.App" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:views="clr-namespace:TeysserApp.Views" 
    xmlns:vm="clr-namespace:TeysserApp.ViewModels" 
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"> 

<Application.Resources> 
    <vm:ViewModelLocator x:Key="Locator" /> 
    <ResourceDictionary> 
     <DataTemplate DataType="{x:Type vm:ConnexionViewModel}"> 
      <view:ConnexionView /> 
     </DataTemplate> 
     <DataTemplate DataType="{x:Type vm:InscriptionViewModel}"> 
      <view:InscriptionView /> 
     </DataTemplate> 
    </ResourceDictionary> 
    <local:LocalizedStrings xmlns:local="clr-namespace:TeysserApp" x:Key="LocalizedStrings"/> 
</Application.Resources> 

    <Application.ApplicationLifetimeObjects> 
     <!--Objet requis qui gère les événements de durée de vie pour l'application--> 
     <shell:PhoneApplicationService 
      Launching="Application_Launching" Closing="Application_Closing" 
      Activated="Application_Activated" Deactivated="Application_Deactivated"/> 
    </Application.ApplicationLifetimeObjects> 

</Application> 

спасибо за вашу помощь.

ответ

2

В MVVM Light 5 Лоран ввести NavigationService

public ViewModelLocator() 
{ 
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); 

    var navigationService = this.CreateNavigationService(); 

    SimpleIoc.Default.Register<INavigationService>(() => navigationService); 

    SimpleIoc.Default.Register<IDialogService, DialogService>(); 

    SimpleIoc.Default.Register<MainViewModel>(); 
    SimpleIoc.Default.Register<DetailsViewModel>(); 
} 

private INavigationService CreateNavigationService() 
{ 
    var navigationService = new NavigationService(); 
    navigationService.Configure("Details", typeof(DetailsPage)); 
    // navigationService.Configure("key1", typeof(OtherPage1)); 

//From a working project. 
navigationService.Configure("tnc", new System.Uri("/Views/TncAgreement.xaml", System.UriKind.Relative)); 


return navigationService; 
} 

Ваш ViewModel

public class MainViewModel : ViewModelBase 
{ 

private INavigationService navigationService; 

public RelayCommand DetailsCommand { get; set; } 

public MainViewModel(INavigationService navigationService) 
{ 
    this.navigationService = navigationService; 

     //Show Terms and condition agreement; 
     navigationService.NavigateTo("tnc"); 

    DetailsCommand = new RelayCommand(() => 
    { 
     navigationService.NavigateTo("Details", "My data"); 
    }); 
} 
} 

Похожие SO Answer

+0

Я не знаю, почему Frame.navigate или NavigationService не работают. У меня есть следующая ошибка для моего Frame.navigate: Не удается преобразовать System.String в System.Uri. Для моего NavigationService. Навигация: для свойства требуется ссылка на объект. Метод или нестатическое поле «NavigationService.Navigate (Uri) –

+0

Я обновил ответ, если у вас все еще возникает проблема с добавлением PLS с подробной информацией о том, какая строка выбрала исключение и так далее – Eldho

0

При нажатии кнопки Connexion выполняется метод ExecuteFirstViewCommand(), однако этого не существует, вам необходимо изменить способ работы лямбда ExecuteConnexionViewCommand(). Если это не решит его, вы можете отлаживать код во время выполнения и посмотреть, обновляется ли CurrentViewModel.

enter image description here

Убедитесь, что он заключен в словаре ресурсов!

<Application.Resources> 
    <ResourceDictionary> 
    </ResourceDictionary> 
</Application.Resources> 
+0

я не могу поставить эту Фолля потому что это говорит: DataType не распознается или недоступен. –

+0

Не могли бы вы показать, что вы положили в свой App.Xaml, пожалуйста, –

+0

Я добавил свой App.xaml –

Смежные вопросы