“在使用ItemsSource之前,项集合必须为空。”错误wpf

时间:2016-12-23 19:55:32

标签: c# wpf observablecollection

我正在尝试绑定一个可观察的字符串集合。但是当我启动应用程序时,我收到Exception,在使用ItemsSource之前,Items集合必须为空。在绑定时我没有收集的元素,那么问题是什么呢?

我的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"  />

我的ViewModel(命令和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;
}

2 个答案:

答案 0 :(得分:1)

由于错误试图告诉您,如果您使用ItemsSource来绑定它们,则无法拥有任何项目。
删除<ListBoxItem>

要为绑定项设置模板,请设置<ListBox.ItemTemplate>

答案 1 :(得分:0)

我修复了使用Items.Clear()

清除我的ListBox