I'm practicing MVVM by create a simple ListView
and a Button
. When Button
is clicked, a new item will be added to ListView
. However my implementation doesn't work. I'm using RelayCommand
for the Button
. What did I do wrong?
XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Button x:Name="AddButton" Grid.Row="0" Margin="10" Content="Add Item" Command="{Binding AddCommand}" />
<ListView x:Name="ListViewItems" Grid.Row="1" Margin="10" ItemsSource="{Binding Items}">
<ListView.ItemContainerStyle >
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<TextBox x:Name="Input" FontSize="15"></TextBox>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
ListViewModel
public class ListViewModel : INotifyPropertyChanged
{
private ObservableCollection<ItemModel> items;
public ObservableCollection<ItemModel> Items {
get
{
return this.items;
}
set
{
if (items != value)
{
items = value;
RaisePropertyChanged(nameof(items));
}
}
}
#region Constructor
public ListViewModel()
{
AddCommand = new RelayCommand(
ExecuteCommand);
}
#endregion
#region Button command
public RelayCommand AddCommand;
private void ExecuteCommand()
{
items.Add(new ItemModel());
}
#endregion
#region INotify
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
#endregion
}
Main Window
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ListViewModel();
}
}