我有一个WPF表单,我希望将反序列化的json数据绑定到UI上的datagrid。但在这里,我无法在UI上看到数据网格中的值。
JSON response:
Firstly, my json response is in the below format:
{
"results":
[
{"type": "upload", "status": "new","data": {"uuid":"f7e98"},"device_id": "123"},
{"type": "upload", "status": "new","data": {"uuid":"f8fc1"},"device_id": "456"},
{"type": "upload", "status": "new","data": {"uuid":"fgff1"},"device_id": "678"},
{"type": "upload", "status": "new","data": {"uuid":"yuki1"},"device_id": "786"},
{"type": "upload", "status": "new","data": {"uuid":"rtyi1"},"device_id": "654"}
]
}
类:
public class UploadStatusList
{
public List<UploadStatus> results;
}
public class UploadStatus
{
public string type {get;set;}
public string status {get;set;}
public string device_id {get;set;}
public Data data {get;set;}
}
public class Data
{
public string uuid {get;set;}
}
这是我的主窗口.xaml.cs
的 MainWindow.xaml.cs:
public partial class MainWindow : Window
{
// Dependency Property
public static readonly DependencyProperty actionListProperty =
DependencyProperty.Register("actionList", typeof(ObservableCollection<UploadStatusList>),
typeof(MainWindow), new FrameworkPropertyMetadata(null));
// .NET Property wrapper
public ObservableCollection<UploadStatusList> actionList
{
get { return (ObservableCollection<UploadStatusList>)GetValue(actionListProperty); }
set { SetValue(actionListProperty, value); }
}
public MainWindow()
{
InitializeComponent();
//Code Block for httpwebRequest here
//JSON Response String
string json = stringbuilder.ToString();
//Newtonsoft.Json.JsonConvert.Deserialize<UploadStatusList>(json) returns null for me here,so using Javascript serializer. No idea why !?
UploadStatusList list = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<UploadStatusList>(json);
foreach (var item in list.results)
{
Debug.Print("id: {0}, name: {1}", item.status, item.device_id);
}
}
}
以下是我的主窗口.XAML ...我是xaml的新手,所以不确定我是否遗漏了任何东西 的 MainWindow.xaml:
<TabItem x:Name="UploadList" Header="Upload List" HorizontalAlignment="Left" Width="77" Margin="-2,-2,0,2">
<Grid Margin="0,0,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="124*"/>
<ColumnDefinition Width="107*"/>
</Grid.ColumnDefinitions>
<Button x:Name="Button" Content="Refresh" Margin="14,40,0,361" HorizontalAlignment="Left" Width="120" Click="Button_Click"/>
<DataGrid Margin="14,79,10,58" x:Name="Access_DataGrid" IsReadOnly="True" ItemsSource="{Binding actionList.results}" IsSynchronizedWithCurrentItem="True" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="status" Binding="{Binding status}" />
<DataGridTextColumn Header="device id" Binding="{Binding device_id}" />
<DataGridTextColumn Header="type" Binding="{Binding type}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</TabItem>
答案 0 :(得分:0)
你做得很好但只需要在ItemSource的Binding中添加ElemmentName或使用DataContext。
<Window x:Name="mainWindow".....>
<... ItemsSource="{Binding actionList.results, ElementName=mainWindow}".....