如何在WPF中用DelegateCommand从列表中填充ListBox



我在尝试填充ListBox时遇到了一个问题。我的xaml文件中有一个按钮:

<Button Content="Show" Command="{Binding ShowSongsBy}" ... >

我还有一个列表框:

<ListBox x:Name="sorted" ItemsSource="{Binding SortedListVM}" ... >

在我的ViewModel中,我有:

private List<string> _sortedList;
public List<string> SortedListVM
{
set
{
_sortedList = value;
onPropertyChanged();
}
get { return _sortedList; }
}

public event PropertyChangedEventHandler PropertyChanged;
public void onPropertyChanged([CallerMemberName]string prop = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}

当我按下按钮时,这就是发生的情况(也在ViewModel中(:

public ICommand ShowSongsBy
{
get
{
return new DelegateCommand((obj) =>
{
SortedListVM = new List<string>();
List<string> testlist = new List<string>();
testlist.Add("1");
testlist.Add("2");
foreach (string i in testlist)
{
SortedListVM.Add(i);
}
});
}
}

我希望在ListBox中看到的内容:"1"one_answers"2"。相反,我看到的是:只有"1">

我搞不清出了什么问题。此外,如果我将代码更改为:

public ICommand ShowSongsBy
{
...
foreach (string i in testlist)
{
SortedListVM.Add(i);
}
SortedListVM.Add("Test1");
...

我看到了我希望在ListBox中看到的内容:"1"、"2"one_answers"Test1"。

如果我只想列出"1"one_answers"2",该怎么办?

我的DelegateCommand类:

class DelegateCommand : ICommand
{
private Action<object> execute;
private Func<object, bool> canExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public DelegateCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return this.canExecute == null || this.canExecute(parameter);
}
public void Execute(object parameter)
{
this.execute(parameter);
}
}    

谢谢。

使用ObservableCollection而不是List

private ObservableCollection<string> _sortedList;
public ObservableCollection<string> SortedListVM
{
get => _sortedList;
set
{
_sortedList = value;
onPropertyChanged();
}
}

用它做你想做的事。就像你用List操作一样。

当您对集合进行任何更改时,ListBox将动态更新其布局。

最新更新