[尝试填充列表框时遇到问题。我的xaml文件中有一个按钮:
<Button Content="Show" Command="{Binding ShowSongsBy}" ... >
我也有一个ListBox:
<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); } }); } }
我希望在列表框中看到:“ 1”和“ 2”。我看到的是:只是“ 1”
我不知道是什么问题。另外,如果我将代码更改为此:
public ICommand ShowSongsBy { ... foreach (string i in testlist) { SortedListVM.Add(i); } SortedListVM.Add("Test1"); ...
我看到了我希望在列表框中看到的内容:“ 1”,“ 2”和“ Test1”。
如果我只希望列出“ 1”和“ 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); } }
谢谢。
[尝试填充列表框时遇到问题。我的xaml文件中有一个按钮:
使用ObservableCollection
代替List
。
private ObservableCollection<string> _sortedList;
public ObservableCollection<string> SortedListVM
{
get => _sortedList;
set
{
_sortedList = value;
onPropertyChanged();
}
}