我是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事件做到這一點?
再說一遍,如果我這樣做是錯誤的,讓我知道並指向正確的方向。謝謝
命令是要走的路! –
這就是我想的但我不確定。我花了一些時間研究ICommand,並能夠使其工作。謝謝! – Chris