2016-12-23 18 views
0

私は観察可能な文字列のコレクションをバインドしようとしています。しかし、アプリを起動すると、ItemsSourceを使用する前にアイテムコレクションが空でなければならないという例外が表示されます。私はそれが束縛されているときにコレクションに要素がないので、何が問題なのでしょうか?"ItemsSourceを使用する前にItemsコレクションを空にする必要があります" error wpf

私の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; 
} 

答えて

1

エラーはあなたを教えしようとしているとして、あなたがそれらをバインドするItemsSourceを使用する場合は、すべてのアイテムを持つことができません代わりに。
<ListBoxItem>を削除してください。

バインドされたアイテムのテンプレートを設定するには、<ListBox.ItemTemplate>と設定します。

+0

)(それはItems.Clearと私のリストボックスをクリアしますが、両方の世界(主に)のベストを引き出すために、 'CompositeCollection'を使用することができます(注)固定。 – BradleyDotNET

0

私は

関連する問題