【问题标题】:“Items collection must be empty before using ItemsSource.” error wpf“在使用 ItemsSource 之前,Items 集合必须为空。”错误 wpf
【发布时间】:2016-12-23 19:55:32
【问题描述】:

我正在尝试绑定一个可观察的字符串集合。但是当我启动一个应用程序时,我收到异常,即在使用 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;
}

【问题讨论】:

    标签: c# wpf observablecollection


    【解决方案1】:

    正如错误试图告诉你的那样,如果你使用ItemsSource 来绑定它们,你就不能拥有任何项目。
    删除你的&lt;ListBoxItem&gt;

    要为绑定项目设置模板,请设置&lt;ListBox.ItemTemplate&gt;

    【讨论】:

    • 请注意,您可以使用CompositeCollection 来获得两全其美(大多数情况下)。
    【解决方案2】:

    我修复了它用 Items.Clear() 清除我的 ListBox

    【讨论】:

      猜你喜欢
      • 2021-07-19
      • 2016-03-23
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      • 2012-03-04
      • 2013-08-08
      • 2012-08-02
      相关资源
      最近更新 更多