2013-10-21 102 views
4

我是MVVM和WPF的新手,但我知道MVVM中發生了什麼。在mainwindow中的用戶控件之間切換時遇到問題。在我的應用程序中,我有: 帶有日誌和2個鏈接的MainWindow.xaml:顯示全部並創建新的。當然,我有ViewModel。我有2個更多的UserControls:ShowAll和Create ViewModels和它的所有邏輯(添加數據等)。當我點擊鏈接時,如何顯示創建表單,或點擊ShowAll時顯示全部?WPF MVVM開關usercontrols

在windowForms我只是藏在UC,這裏布多是背後沒有代碼:)

我MainWindow.xaml:

<Window x:Class="Test.Views.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="300" Width="300"> 
    <Grid> 
     <StackPanel> 
      <TextBox Text="{Binding Name}"/> 
      <Button Content="Change" Command="{Binding ChangeCommand}"/> 
     </StackPanel> 
    </Grid> 
</Window> 

我MainWindowViewModel:

class MainWindowViewModel : BaseViewModel 
{ 
    private Person _person; 
    private BaseCommand _changeCommand; 

    public MainWindowViewModel() 
    { 
     _person = new Person(); 
    } 

    public string Name 
    { 
     get 
     { 
      return _person.Name; 
     } 
     set 
     { 
      if (_person.Name != value) 
       _person.Name = value; 
      OnPropertyChanged(() => Name); 
     } 
    } 

    public ICommand ChangeCommand 
    { 
     get 
     { 
      if (_changeCommand == null) 
       _changeCommand = new BaseCommand(() => change()); 
      return _changeCommand; 
     } 
    } 

    private void change() 
    { 
     _person = new Person(); 
     Name = _person.Imie; 
    } 
} 

在創建和勾住ShowAll有沒有代碼。在xaml中只有一個標籤,VM是空的。只是爲了測試。

感謝您的幫助!

+2

發佈相關代碼和XAML。 BTW MVVM並不意味着沒有代碼。 MVVM意味着不要將業務邏輯置於代碼之後。 –

回答

8

您可以使用ContentControl根據綁定到ContentControl的ViewModel的類型顯示特定的DataTemplate

http://www.japf.fr/2009/03/thinking-with-mvvm-data-templates-contentcontrol/

綁定到勾住ShowAll按鈕可以簡單地改變你的主視圖模型是什麼是綁定到內容控件的屬性的命令。

+0

是的,聽起來是正確的... 他也可以使用一些框架或消息類。 – Noctis

+0

非常感謝!這是如此簡單:)順便說一句,這些DataTemplates偉大的事情。您可以在不同的控件中使用一種類型。哇 :) – Chris