[英]How to bind c# object to WPF datagrid
我将 JSON object 反序列化为 C#,然后将数据网格 ItemSource/DataContext 与其相等。 自动生成列工作正常,但我只是想从列表中获取特定列,它似乎没有工作。 我还查看了以下答案,但它似乎对我没有帮助。 WPF DataGrid 绑定不起作用这是我的代码:
public class ARCGISapi
{
[JsonProperty("locations")]
public LocationElement[] Locations { get; set; }
}
public class LocationElement
{
[JsonProperty("address")]
public string Address { get; set; }
[JsonProperty("location")]
public LocationLocation Location { get; set; }
[JsonProperty("score")]
public long Score { get; set; }
[JsonProperty("attributes")]
public Attributes Attributes { get; set; }
}
private void PopulateGrid(string result)
{
ARCGISapi apiWrapper = new ARCGISapi();
apiWrapper = JsonConvert.DeserializeObject<ARCGISapi>(result);
ResultsDataGrid.DataContext = apiWrapper.Locations;
ResultsDataGrid.ItemsSource = apiWrapper.Locations;
}
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Locations}" x:Name="ResultsDataGrid">
<DataGrid.Columns>
<DataGridTextColumn Header="Score" Binding="{Binding Score}" />
<DataGridTextColumn Header="Location" Binding="{Binding Location.X}" />
</DataGrid.Columns>
</DataGrid>
假设ARCGISapi
的一个实例被设置为 DataGrid(或 Window)的 DataContext,那么ItemsSource
应该绑定到Locations
而不是LocationElement
(属性的名称而不是类型的名称)。
在 XML 改变这个
ItemsSource="{Binding LocationElement}"
对此
ItemsSource="{Binding Locations}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.