在DataGrid上绑定类数据

时间:2018-07-22 13:38:44

标签: c# wpf wpfdatagrid

我在显示Customer类的Address部分时遇到了麻烦,我制作了一个Location属性来显示整个地址,但是当我运行应用程序时,该地址丢失了。如您在图像中看到的,客户将绑定到数据网格。

enter image description here

如果我找不到解决方案,我只会将地址属性添加到我的Customer类中,但我想尽可能解决。

谢谢。

示例实例:

var customer = new Customer
        {
            FirstName = fNameTxt.Text, LastName = lNameTxt.Text, Email = emailTxt.Text, Phone = phTxt.Text,
            Address = new Address { Street = streetTxt.Text, Suburb = suburbTxt.Text, City = cityTxt.Text, Country = countryTxt.Text }
        };

XAML :(数据网格)

<DataGrid x:Name="customerDataGrid" HorizontalAlignment="Left" Height="205" Margin="10,10,0,0" Grid.Row="1" VerticalAlignment="Top" Width="780" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
            <DataGridTextColumn Header="Full Name" Binding="{Binding FullName}"/>
            <DataGridTextColumn Header="Phone" Binding="{Binding Phone}"/>
            <DataGridTextColumn Header="Email" Binding="{Binding Email}"/>
            <DataGridTextColumn Header="Address" Binding="{Binding Location}"/>
        </DataGrid.Columns>
    </DataGrid>

课程:

public class Customer
{
    public int Id { get; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { get { return FirstName + " " + LastName; } }
    public string Phone { get; set; }
    public string Email { get; set; }
    public Address Address { get; set; }

    private static int counter = 0;
    public Customer()
    {
        this.Id = System.Threading.Interlocked.Increment(ref counter);
    }
}

public class Address
{
    public string Street { get; set; }
    public string Suburb { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string Location { get { return string.Format($"{Street}, {Suburb}, {City}, {Country}"); } }
}

1 个答案:

答案 0 :(得分:1)

<DataGridTextColumn Header="Email" Binding="{Binding Email}"/>
<DataGridTextColumn Header="Address" Binding="{Binding Location}"/>

电子邮件是客户类的属性,因此可以成功解析绑定Email中的绑定路径{Binding Path=Email}并显示电子邮件。

但是这里{Binding Path=Location}的绑定路径Location是错误的。位置是地址类的属性。客户只有地址类型的地址属性。这使Location成为嵌套属性。绑定应更改:

<DataGridTextColumn Header="Email" Binding="{Binding Email}"/>
<DataGridTextColumn Header="Address" Binding="{Binding Address.Location}"/>

将其与c#代码进行比较:

var c = new Customer();
string location = c.Location; // ! won't compile
string location = c.Address.Location; // will compile, but give NullReferenceException, because Address wasn't initialized

最后一点:Visual Studio应该在“输出”窗口中写了关于在Customer对象中找不到Location属性的多个绑定错误。如果绑定不起作用,请始终检查输出