我有一个ListView,并且由于它支持多个选择,所以我有一个按钮,用于收集所有SelectedItems并使用CommandParameter传递它们。对此我非常陌生,我真的不知道该如何使用参数。将列表传递给ViewModel后,如何访问该列表?请参见以下代码:
<ListView x:Name="ListView" ItemsSource="{Binding myModel.myCollection}">
<Button Command="{Binding SelectBtnOnClickCommand}" CommandParameter="{Binding SelectedItems, ElementName=ListView}">
public class SiteListViewModel
{
public ICommand AddBtnOnClickCommand { get; }
private ICommand _selectBtnOnClickCommand;
public ICommand SelectBtnOnClickCommand
{
get
{
if (_selectBtnOnClickCommand == null)
_selectBtnOnClickCommand = new RelayCommand(o =>
{
var selectedSites = (o as IList);
if (selectedSites != null)
{
foreach (var model in selectedSites.OfType<SiteUrlsModel>())
{
//
}
}
});
return _selectBtnOnClickCommand;
}
}
private readonly IWindowService _windowService;
public static SiteUrlsModel SiteUrlsModel { get; } = new SiteUrlsModel();
public ObservableCollection<SiteUrlsModel> SelectedSites { get; set; }
private readonly ClientContext _clientContext = new ClientContext();
public SiteListViewModel(IWindowService windowService)
{
_windowService = windowService;
AddBtnOnClickCommand = new RelayCommand(AddBtnOnClick);
//SelectBtnOnClickCommand = new RelayCommand(SelectBtnOnClick);
RefreshSiteListView();
}
public void AddBtnOnClick()
{
_addSiteWindow = new AddSite(this);
_addSiteWindow.Show();
}
public void SelectBtnOnClick(ObservableCollection<SiteUrlsModel> checkedList)
{
foreach (var site in checkedList)
{
site.IsChecked = true;
}
}
public void RefreshSiteListView()
{
var siteUrlsCollection = new ObservableCollection<SiteUrlsModel>(_clientContext.PopulateList());
SiteUrlsModel.SiteUrlsCollection = siteUrlsCollection;
}
}
public class RelayCommand : ICommand
{
private readonly Action<object> _actionWithObject;
public RelayCommand(Action<object> actionWithObject)
{
_actionWithObject = actionWithObject;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
if (parameter != null)
_actionWithObject(parameter);
else
_actionWithObject(parameter);
}
public event EventHandler CanExecuteChanged;
}
答案 0 :(得分:1)
ListView.SelectedItems
是IList
:
private ICommand _selectBtnOnClickCommand;
public ICommand SelectBtnOnClickCommand
{
get
{
if (_selectBtnOnClickCommand == null)
_selectBtnOnClickCommand = new RelayCommand(o =>
{
var selectedSites = (o as IList);
if (selectedSites != null)
{
foreach (var model in selectedSites.OfType<SiteUrlsModel>())
{
//
}
}
});
return _selectBtnOnClickCommand;
}
}