I am trying to bind an observable collection of strings. But when i launch an app, I receive Exception that Items collection must be empty before using ItemsSource. I have no elements in collection when it is binding, so what can be the issue?
My Xaml
<ListBox ItemsSource="{Binding Users}" Margin="10,77,805,228" Grid.RowSpan="2">
<ListBoxItem>
<DataTemplate>
<StackPanel Orientation="Horizontal">
</StackPanel>
</DataTemplate>
</ListBoxItem>
</ListBox>
<Button x:Name="AddUserButton" Content="Додати" Command="{Binding AddUserCommand}" RenderTransformOrigin="0.512,1.9" />
My ViewModel (command and observablecollection)
public class UsersTabViewModel : ViewModelBase
{
private ObservableCollection<string> users;
private string text;
private ICommand addUserCommand;
private bool _canExecute;
public UsersTabViewModel()
{
_canExecute = true;
Users = new ObservableCollection<string>();
}
public ObservableCollection<string> Users { get; set; }
public ICommand AddUserCommand
{
get
{
return addUserCommand ?? (addUserCommand = new CommandHandler(() => AddUserAction(), _canExecute));
}
}
public string Text
{
get
{
return text;
}
set
{
text = value;
}
}
//text is bound to here
private void AddUserAction()
{
Users.Add("collection");
}
public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action();
}
}
public event PropertyChangedEventHandler PropertyChanged;
}