无法从DataGrid问题中转换.SelectedItems

Kev*_*vin 1 c# wpf datagrid .net-4.5

好吧......星期五,天色已晚,我有点倦怠......

码:

public partial class SiteSelection : Window
{

    private IList<IISBrowser.IISSiteList> _siteList;

    public IList<IISBrowser.IISSiteList> SelectedItemsList { get; set; }

    public SiteSelection(IList<IISBrowser.IISSiteList> _sl)
    {
        InitializeComponent();
        _siteList = _sl;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.dg_Sites.ItemsSource = _siteList;
    }

    private void btnSelectSites_Click(object sender, RoutedEventArgs e)
    {
        SelectedItemsList = (IList<IISBrowser.IISSiteList>)dg_Sites.SelectedItems;
        this.Close();
    }
Run Code Online (Sandbox Code Playgroud)

填充数据网格,我可以在其中选择项目.带按钮(btnSelectSites)

我一直在 Unable to cast object of type 'System.Windows.Controls.SelectedItemCollection' to type 'System.Collections.Generic.IList 1[Backup.S3.Store.IISBrowser+IISSiteList]'.

并且不明白为什么......这是我的理解,因为我IList<>在申请ItemSource 时设置了这个,我会返回相同的数据类型..

我怎样才能解决这个问题?

编辑:

已经尝试过这里的解决方案:在wpf数据网格中键入所选项目的列表,这与其他解决方案类似......其中没有一个有效.

Gra*_*ICA 6

使用此替代方法,将集合转换为原始类型:

SelectedItemsList = dg_Sites.SelectedItems
                            .Cast<IISBrowser.IISSiteList>()
                            .ToList();
Run Code Online (Sandbox Code Playgroud)

在链接的答案中,list将是(在您的情况下)dg_Sites.SelectedItems集合.

您可能还需要添加using System.Linq;到班级的顶部,如果它还没有.