【问题标题】:LongListSelector on WP8 linq-to-sql binding issueWP8 linq-to-sql 绑定问题上的 LongListSelector
【发布时间】:2013-08-20 18:21:11
【问题描述】:

我正在构建我的第一个 WP8 应用程序,它通过 linq-to-sql 连接到数据库,我想在 LongListSelector 中显示数据。但是在模拟器中启动后什么都没有出现,只是黑屏。

请问我哪里出错了?我使用 WCF 连接

这是 MainPage.xaml.cs

    using PhoneApp1.Resources;
using PhoneApp1.ToursServiceReference1;


    namespace PhoneApp1

{
    public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        // Sample code to localize the ApplicationBar
        //BuildLocalizedApplicationBar();
    }
    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
        ToursServiceReference1.ToursService1Client serviceClient = new ToursServiceReference1.ToursService1Client();

        serviceClient.GetAllKlientsCompleted += new EventHandler<ToursServiceReference1.GetAllKlientsCompletedEventArgs>(serviceClient_GetAllKlientsCompleted);

        serviceClient.GetAllKlientsAsync();
    }
    private void serviceClient_GetAllKlientsCompleted(object sender, ToursServiceReference1.GetAllKlientsCompletedEventArgs e)
    {
        if (e.Result != null)
        {
            LLS.ItemsSource = e.Result;
        }

    }

t

这是 MainPage.xaml

<phone:PhoneApplicationPage
x:Class="PhoneApp1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">

<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="ToursDataTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Margin="10" Text="{Binding name}"/>

        </StackPanel>
    </DataTemplate>
    <Style x:Key="LongListSelectorStyle1" TargetType="phone:LongListSelector">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="phone:LongListSelector">
                    <Grid Background="{TemplateBinding Background}" d:DesignWidth="480" d:DesignHeight="800">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="ScrollStates">
                                <VisualStateGroup.Transitions>
                                    <VisualTransition GeneratedDuration="00:00:00.5"/>
                                </VisualStateGroup.Transitions>
                                <VisualState x:Name="Scrolling"/>
                                <VisualState x:Name="NotScrolling"/>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>

                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>


</phone:PhoneApplicationPage.Resources>

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="0*"/>
    </Grid.RowDefinitions>

    <!-- LOCALIZATION NOTE:
        To localize the displayed strings copy their values to appropriately named
        keys in the app's neutral language resource file (AppResources.resx) then
        replace the hard-coded text value between the attributes' quotation marks
        with the binding clause whose path points to that string name.

        For example:

            Text="{Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}"

        This binding points to the template's string resource named "ApplicationTitle".

        Adding supported languages in the Project Properties tab will create a
        new resx file per language that can carry the translated values of your
        UI strings. The binding in these examples will cause the value of the
        attributes to be drawn from the .resx file that matches the
        CurrentUICulture of the app at run time.
     -->

    <!--TitlePanel contains the name of the application and page title-->

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"/>
    <TextBlock HorizontalAlignment="Left" Margin="60,44,0,-91" Grid.Row="1" TextWrapping="Wrap" Text="Připojení SQL" VerticalAlignment="Top" Height="47" Width="348" TextAlignment="Center" FontWeight="Bold" FontSize="36"/>
    <phone:LongListSelector x:Name="LLS" HorizontalAlignment="Left" ItemsSource="{Binding name}" ItemTemplate="{StaticResource ToursDataTemplate}" Height="407" Margin="47,164,0,-571" Grid.RowSpan="2" VerticalAlignment="Top" Width="365"/>

    <!--Uncomment to see an alignment grid to help ensure your controls are
        aligned on common boundaries.  The image has a top margin of -32px to
        account for the System Tray. Set this to 0 (or remove the margin altogether)
        if the System Tray is hidden.

        Before shipping remove this XAML and the image itself.-->
    <!--<Image Source="/Assets/AlignmentGrid.png" VerticalAlignment="Top" Height="800" Width="480" Margin="0,-32,0,0" Grid.Row="0" Grid.RowSpan="2" IsHitTestVisible="False" />-->
</Grid>

很抱歉提供了这么大的代码,但到目前为止我还不知道错误可能出在哪里,所以我发布了完整的代码。

感谢大家的宝贵时间。

【问题讨论】:

  • 您是否确认您确实从您的网络服务收到了项目?您是否确认您的e.Result 可以由您的LongListSelector 中的ItemsSource 处理?

标签: c# wcf linq-to-sql windows-phone-8


【解决方案1】:

编辑:哎呀,对不起,我没有读到您为此使用 WCF,因为我认为 WebAPI 在这里会没问题(关于您对 web api 和引用的问题你的问题在这里)。但也许你不需要坚持使用 WCF 并且可以使用其他技术?

Marek,请再次查看https://stackoverflow.com/a/18271995/959687,了解基础知识。我正在编写以下代码,因此之后可能需要对其进行改进。但它会告诉你它是如何完成的。

我将向您展示如何使用 Web 服务中的项目填充您的 LongListSelector。

首先我们需要我们的数据传输对象(DTO):

[JsonObject]
public class ListDTO
{
  [JsonProperty]
  public IEnumerable<string> Items { get; set; }
}

那么你需要一个控制器:

public class ListController : ApiController
{
  [HttpGet]
  public ListDTO Get() 
  {
    return new ListDTO() 
    {
      Items = new List<string>() 
      {
        "Item 1",
        "Item 2",
      },
    };
  }
}

然后您需要从应用内的服务中检索这些项目:

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
  LoadFromWebservice();
}

private async void LoadFromWebservice()
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://thewebservice.tld/");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    await client.GetStreamAsync("api/list/get")
        .ContinueWith(result =>
    {
        var stream = result.Result;
        var serializer = new JsonSerializer(); // this is json.net serializer
        using (var streamReader = new StreamReader(stream))
        {
            using (var jsonReader = new JsonTextReader(streamReader))
            {
                var theList = serializer.Deserialize<ListDTO>(jsonReader);
                Dispatcher.BeginInvoke(() => LLS.ItemsSource = theList.Items.ToList());
            }
        }
    });
}

您现在可以使用 ling-to-sql 从数据库或其他东西中检索控制器中的项目。随心所欲,随心所欲。 :-)

但请注意:我不建议这样做,因为它与您的用户界面耦合太多。此示例向您展示了从 Web 服务获取数据的基本知识。

我建议您查看 MVVM 模式 (http://en.wikipedia.org/wiki/Model_View_ViewModel),构建一个视图模型并将您的视图绑定到该视图模型。一种方法是使用 MVVM 灯:http://mvvmlight.codeplex.com/

其他信息

【讨论】:

  • 非常感谢!我要试试。请问我应该使用什么参考才能使用json?
  • @Marek 这是 JSON.net(WebAPI(当前版本)默认使用它)。要将其包含到您的 Windows Phone 8 项目中,请使用 NuGet (nuget.org/packages/NewtonSoft.Json) Install-Package NewtonSoft.Json
  • 我安装了它,但当我尝试插入您的代码时仍然出现错误:找不到类型或命名空间'...'(您是否缺少 using 指令或程序集引用?)
  • 找不到哪种类型? JsonSerializer? JsonTextReader?
  • 大约有 16 个,包括 JsonTextReader 和 JsonSerializer。我应该改变什么?
猜你喜欢
  • 2017-02-01
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
相关资源
最近更新 更多