将List <myobject>绑定到DataGrid?当我尝试时,我得到一个“TargetInvocationException”

时间:2015-07-27 01:00:30

标签: c# wpf xaml data-binding datagrid

我正在尝试将List<MyObject>绑定到WPF中的DataGrid,而不是使用MyObject[]数组。每当我尝试这样做时,我都会得到一个未处理的TargetInvocationException

我的对象:

public class Website
{
    public string WebsiteName { get; set; }
    public string WebsiteAddress { get; set; }
    private LoginCredentials Credentials { get; set; }

    public bool UniquePassword { get; set; } //If uses uses a unique password on this site
    public bool LoginToSite { get; set; }
    public bool UsesUsernameAndDomain { get; set; }

    public string GetUsername()
    {
        if(UsesUsernameAndDomain)
        {
            return Credentials.Username + "@" + Credentials.EmailDomain;
        }
        else
        {
            return Credentials.Username;
        }
    }

    public void SetUsername(string value)
    {
        Credentials.Username = value;
    }

    public void SetDomain(string value)
    {
        Credentials.EmailDomain = value;
    }
}

ViewModel代码段:

    private List<Website> m_Websites;
    public List<Website> Websites
    {
        get { return m_Websites; }
        set { m_Websites = value; RaisePropertyChanged("Websites"); }
    }

XAML:

        <DataGrid ItemsSource="{Binding}"
                  DataContext="{Binding Websites}"
                  AutoGenerateColumns="False"
                  FontSize="14"
                  VerticalAlignment="Center"
                  VerticalContentAlignment="Center">

当我尝试使用数组时,它按预期运行。我想使用一个集合来处理它附带的附加行为。我在这里做错了什么?

注意:我对WPF很新,并且最近才对数据绑定感到困惑,不要以为我知道WPF的细节或它的范例。

1 个答案:

答案 0 :(得分:0)

我犯了一个很新手的错误。绑定到List属性时,我没有实例化List类型的私有字段。

我试图绑定到:

    private List<Website> m_Websites;
    public List<Website> Websites
    {
        get { return m_Websites; }
        set { m_Websites = value; RaisePropertyChanged("Websites"); }
    }

我需要实例化一个新列表:

    private List<Website> m_Websites = new List<Websites>();