簡體   English   中英

來自Xaml中的Json的DataBinding?

[英]DataBinding From Json in xaml?

我正在制作WP7應用,並以json的形式從Webapi取回數據。 我想知道如何對其進行數據綁定? 我需要創建一個具體的類還是可以只使用JArray?

[{"Id":"fe480d76-deac-47dd-af03-d5fd524f4086","Name":"SunFlower Seeds","Brand":"PC"}]

  JArray jsonObj = JArray.Parse(response.Content);
   this.listBox.ItemsSource = jsonObj;


        <ListBox x:Name="listBox" FontSize="26" Margin="0,67,0,0">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Id}" Width="100"/>
                        <TextBlock Text="{Binding Brand}" Width="100"/>
                        <TextBlock Text="{Binding Name}" Width="100"/>
                    </StackPanel>

                </DataTemplate>

            </ListBox.ItemTemplate>

        </ListBox>

與WPF綁定時,需要使用“屬性”。 創建一個強類型的對象,然后反序列化JSON。

創建您的對象:

public class MyObject
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Brand { get; set; }
}

這是一個非常寬松的綁定示例,它基於您將如何設置列表框的ItemsSource來進行綁定:

string json = "[{\"Id\":\"fe480d76-deac-47dd-af03-d5fd524f4086\",\"Name\":\"SunFlower Seeds\",\"Brand\":\"PC\"}]";

var jsonObj = JArray.Parse( json );

var myObjects = jsonObj.Select( x => JsonConvert.DeserializeObject<MyObject>( x.ToString() ) );

this.listBox.ItemsSource = myObjects;

注意:我還沒有使用json.net,所以可能有一種更好的方法可以用json.net反序列化我發布的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM