2013-04-17 28 views
0

我是MVVM的新手,仍然試圖掌握它,所以讓我知道如果我把它設置錯了。我有一個帶有ListView的UserControl。我使用ViewModel中的數據填充此ListView,然後將控件添加到我的MainView。在我的MainView上,我有一個按鈕,我想用它來添加一個項目到ListView。以下是我有:從MainView與ViewModel進行通信

型號

public class Item 
{ 
    public string Name { get; set; } 

    public Item(string name) 
    { 
     Name = name; 
    } 
} 

視圖模型

public class ViewModel : INotifyPropertyChanged 
{ 

    #region INotifyPropertyChanged Members 

    public event PropertyChangedEventHandler PropertyChanged; 

    private void OnPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
    #endregion 

    private ObservableCollection<Item> _itemCollection; 

    public ViewModel() 
    { 
     ItemCollection = new ObservableCollection<Item>() 
     { 
      new Item("One"), 
      new Item("Two"), 
      new Item("Three"), 
      new Item("Four"), 
      new Item("Five"), 
      new Item("Six"), 
      new Item("Seven") 
     }; 
    } 

    public ObservableCollection<Item> ItemCollection 
    { 
     get 
     { 
      return _itemCollection; 
     } 
     set 
     { 
      _itemCollection = value; 
      OnPropertyChanged("ItemCollection"); 
     } 
    } 
} 

視圖(XAML)

<UserControl.Resources> 
    <DataTemplate x:Key="ItemTemplate"> 
     <StackPanel Orientation="Vertical"> 
      <Label Content="{Binding Name}" /> 
     </StackPanel> 
    </DataTemplate> 
</UserControl.Resources> 

<UserControl.DataContext> 
    <local:ViewModel /> 
</UserControl.DataContext> 

<Grid> 
    <ListView ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding ItemCollection}"> 

    </ListView> 
</Grid> 

主窗口

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     this.mainContentControl.Content = new ListControl(); 
    } 

    private void Button_Add(object sender, RoutedEventArgs e) 
    { 

    } 
} 

主窗口(XAML)現在

<Grid> 
    <DockPanel> 
     <StackPanel DockPanel.Dock="Top" Orientation="Horizontal"> 
      <Button Width="100" Height="30" Content="Add" Click="Button_Add" /> 

     </StackPanel> 
     <ContentControl x:Name="mainContentControl" /> 
    </DockPanel> 
</Grid> 

,從我的理解,我應該能夠僅僅ItemCollection一個項目,它會在視圖中更新。我怎麼從Button_Add事件做到這一點?

再說一遍,如果我這樣做是錯誤的,讓我知道並指向正確的方向。謝謝

回答

2

你不應該直接與控件進行交互。

你需要做的是定義一個Command(一個實現了ICommand接口的類)並在你的ViewModel上定義這個命令。

然後您將Button的命令屬性綁定到ViewModel的此屬性。在ViewModel中,你可以執行命令並直接添加一個項目到你的列表中(因此listview將通過自動數據綁定得到更新)。

這個環節應該提供更多信息:

http://msdn.microsoft.com/en-us/library/gg405484(v=pandp.40).aspx#sec11

+0

命令是要走的路! –

+0

這就是我想的但我不確定。我花了一些時間研究ICommand,並能夠使其工作。謝謝! – Chris