LongListSelector在WP8 LINQ到SQL绑定问题 [英] LongListSelector on WP8 linq-to-sql binding issue

查看:161
本文介绍了LongListSelector在WP8 LINQ到SQL绑定问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建设我认为通过LINQ到SQL连接到数据库第一WP8应用程序,我想表明那里LongListSelector数据。但没有在模拟器启动后只出现黑屏。



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



这是MainPage.xaml.cs中



 使用PhoneApp1.Resources; 
使用PhoneApp1.ToursServiceReference1;


命名空间PhoneApp1

{
公共部分类的MainPage:的PhoneApplicationPage
{
//构造
公的MainPage()
{
的InitializeComponent();

//示例代码本地化应用程序任务栏
// BuildLocalizedApplicationBar();
}
私人无效PhoneApplicationPage_Loaded(对象发件人,RoutedEventArgs E)
{
ToursServiceReference1.ToursService1Client serviceClient =新ToursServiceReference1.ToursService1Client();

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

serviceClient.GetAllKlientsAsync();
}
私人无效serviceClient_GetAllKlientsCompleted(对象发件人,ToursServiceReference1.GetAllKlientsCompletedEventArgs E)
{
如果(e.Result!= NULL)
{
LLS。的ItemsSource = e.Result;
}

}

T



这是MainPage.xaml中

 <电话:的PhoneApplicationPage 
X:CLASS = PhoneApp1.MainPage
的xmlns =http://schemas.microsoft.com/winfx/2006/xaml/presentation
的xmlns:X =http://schemas.microsoft.com/winfx / 2006 / XAML
的xmlns:手机=CLR的命名空间:Microsoft.Phone.Controls;装配= Microsoft.Phone
的xmlns:SHELL =CLR的命名空间:Microsoft.Phone.Shell;装配= Microsoft.Phone
的xmlns:D =http://schemas.microsoft.com/expression/blend/2008
的xmlns:MC =http://schemas.openxmlformats.org/markup -compatibility / 2006年的
MC:可忽略=D
的FontFamily ={StaticResource的PhoneFontFamilyNormal}
字号={StaticResource的PhoneFontSizeNormal}
前景={StaticResource的PhoneForegroundBrush }
SupportedOrientations =纵向方向=纵向
壳:SystemTray.IsVisible =真>

<电话:PhoneApplicationPage.Resources>
<的DataTemplate X:键=ToursDataTemplate>
< StackPanel的方向=横向>
< TextBlock的保证金=10文本={结合}名/>

< / StackPanel的>
< / DataTemplate中>
<风格X:键=LongListSelectorStyle1的TargetType =电话:LongListSelector>
< setter属性=背景值=透明/>
< setter属性=前景VALUE ={StaticResource的PhoneForegroundBrush}/>
< setter属性=模板>
< Setter.Value>
<的ControlTemplate的TargetType =电话:LongListSelector>
<网格背景={TemplateBinding背景}D:DesignWidth =480D:DesignHeight =800>
< VisualStateManager.VisualStateGroups>
< VisualStateGroup X:NAME =ScrollStates>
< VisualStateGroup.Transitions>
将; VisualTransition GeneratedDuration =00:00:00.5/>
< /VisualStateGroup.Transitions>
<的VisualState X:NAME =滚动/>
<的VisualState X:NAME =NotScrolling/>
< / VisualStateGroup>
< /VisualStateManager.VisualStateGroups>

< /网格和GT;
< /控件模板>
< /Setter.Value>
< /二传手>
< /样式和GT;


< /电话:PhoneApplicationPage.Resources>

<! - LayoutRoot是所有页面内容放在根格 - >
<电网X:NAME =LayoutRoot背景=透明>
< Grid.ColumnDefinitions>
< ColumnDefinition />
< /Grid.ColumnDefinitions>
< Grid.RowDefinitions>
< RowDefinition高度=自动/>
< RowDefinition高度=0 */>
< /Grid.RowDefinitions> !

< - LOCALIZATION NOTE:
要本地化显示字符串复制他们的价值观,以适当命名的应用程序的中性语言资源文件(AppResources.resx)
键则
相的路径指向字符串名称绑定条款替代属性引号
之间的硬编码的文本值。

为例:

文本={绑定路径= LocalizedResources.ApplicationTitle源= {StaticResource的LocalizedStrings}}

本的结合点模板的名为ApplicationTitle字符串资源。

项目属性选项卡中添加支持的语言将创造每一个可以承载你的
UI字符串的值翻译语言
新的RESX文件。在这些实施例中的结合将导致
的值属性被从该应用程序的
的CurrentUICulture在运行时间相匹配.resx文件绘制。
- >

<! - TitlePanel包含应用程序和页面标题的名字 - >

<! - 的ContentPanel - 在这里放置其他内容 - >
<电网X:名称=的ContentPanelGrid.Row =1保证金=12,0,12,0/>
< TextBlock中的Horizo​​ntalAlignment =左保证金=60,44,0,-91Grid.Row =1TextWrapping =自动换行文本=PřipojeníSQLVerticalAlignment =评出的HEIGHT = 47WIDTH =348TextAlignment =中心粗细=大胆字号=36/>
<电话:LongListSelector X:NAME =LLS的Horizo​​ntalAlignment =左的ItemsSource ={结合NAME}的ItemTemplate ={StaticResource的ToursDataTemplate}HEIGHT =407保证金=47,164,0 - 571Grid.RowSpan =2VerticalAlignment =评出的WIDTH =365/>

<! - 取消注释看到对齐网格,以帮助确保您的控件是
共同边界对齐。该图像具有-32px的顶部保证金
账户系统托盘。将其设为0(或完全消除边距)
如果系统托盘是隐藏的。

出货前删除此XAML和图像本身.-->
<! - <图像源=/资产/ AlignmentGrid.pngVerticalAlignment =评出的HEIGHT =800WIDTH =480保证金=0 -32,0,0电网.Row =0Grid.RowSpan =2IsHitTestVisible =假/> - →;
< /网格和GT;





对不起用于提供大码但我不迄今知道的错误可能是我发表完整的代码。



谢谢大家的时间。


< DIV CLASS =h2_lin>解决方案

修改:Woops,对不起,我没看过你使用WCF对于这一点,因为我想的WebAPI会是确定这里(关于你的问题对Web API和引用在这里你的问题)。但也许你并不需要坚持使用WCF,可以使用其他技术?



马立克,请看看 http://stackoverflow.com/ A /959687分之18271995再次,对于基础知识。我写了下面的代码我的头,所以它可能需要以后改进。但它会告诉你它是如何基本上完成了。



我会告诉你,如何从一个web服务的项目来填充LongListSelector。



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





<预类=郎-CS prettyprint,覆盖> [JSONObject的]
公共类ListDTO
{
[JsonProperty]
公开的IEnumerable<串GT;项目{搞定;组; }
}



然后你需要为这个控制器:



<预类=郎-CS prettyprint-覆盖> 公共类ListController:ApiController
{
[HTTPGET]
公共ListDTO获得()
{
返回新ListDTO()
{
项目=新的List<串>()
{
项目1,
项目2,
},
};
}
}



然后,你将需要检索从服务这些项目你的应用程序中:



<预类=郎-CS prettyprint-覆盖> 私人无效PhoneApplicationPage_Loaded(对象发件人,RoutedEventArgs E)
{
LoadFromWebservice();
}

私人异步无效LoadFromWebservice()
{
HttpClient的客户端=新的HttpClient();
client.BaseAddress =新的URI(HTTP://thewebservice.tld/);
client.DefaultRequestHeaders.Accept.Add(新MediaTypeWithQualityHeaderValue(应用/ JSON));

等待client.GetStreamAsync(API /表/ GET)
.ContinueWith(结果=>
{
VAR流= result.Result;
无功序列化=新JsonSerializer(); //这是json.net串行
使用(VAR的StreamReader =新的StreamReader(流))使用
{
(VAR jsonReader =新JsonTextReader( StreamReader的))
{
变种的thelist = serializer.Deserialize< ListDTO>(jsonReader);
Dispatcher.BeginInvoke(()=> LLS.ItemsSource = theList.Items.ToList()) ;
}
}
});
}

您现在可以使用灵到SQL从检索控制器内的物品数据库什么的。随意做的,任何你想要的。 : - )



但要知道:我不建议这样做这种方式,因为它实在是太多了连接到您的用户界面。此示例显示了非常基本的从Web服务获取数据



我会建议你看一看MVVM模式(的 http://en.wikipedia.org/wiki/Model_View_ViewModel ),建立一个视图模型和绑定您的视图到该视图模型。这样做的一个方法是使用MVVM光: http://mvvmlight.codeplex.com/



其他信息




  • 如果你想测试你的本地机器,请看看这里:的 http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj684580%28v=vs.105%29.aspx

  • 要使用HttpClient的,你需要从安装的NuGet包

  • 要部署的解决方案,让每个人都可以访问它,你需要运行.NET 4.5的网站空间,创建一个部署封装(< A HREF =http://msdn.microsoft.com/en-us/library/dd465323.aspx相对=nofollow> http://msdn.microsoft.com/en-us/library/dd465323.aspx ),并将其上传到服务器

  • 访问您的MS SQL数据库,你可以使用灵到SQL,实体框架,或其他任何.NET支持。


I'm building my first WP8 app that connects via linq-to-sql to Database and I wanted to show there data in LongListSelector. But nothing appears just black screen after starting up in Emulator.

May I ask where do I make mistake? I use WCF to connect

this is 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

this is 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>

Sorry for providing that large code but as I don't know so far where the mistake might be I published full code.

Thank you everyone for your time.

解决方案

Edit: Woops, I'm sorry, I didn't read that you are using WCF for this, since I thought WebAPI will be ok here (regarding to your question to web api and referencing your question here). But maybe you do not need to stick with WCF and can use other technologies?

Marek, please take a look at http://stackoverflow.com/a/18271995/959687 again, for the basics. I'm writing the following code out of my head, so it may need to be improved afterwards. But it will show you how it is basically done.

I will show you, how to populate your LongListSelector with items from a webservice.

At first we need our data transfer object (DTO):

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

Then you need a controller for this:

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

Then you will need to retrieve those items from the service within your app:

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());
            }
        }
    });
}

You can now retrieve your items within the controller with ling-to-sql from a database or something. Feel free to do, whatever you want. :-)

But be aware: I do not recommend it doing it this way, since it is too much coupled to your user interface. This example shows you the very basic of getting data from a webservice.

I will recommend you to take a look at the MVVM pattern (http://en.wikipedia.org/wiki/Model_View_ViewModel), build a viewmodel and bind your view to that viewmodel. A way of doing this is using MVVM light: http://mvvmlight.codeplex.com/

Additional information

这篇关于LongListSelector在WP8 LINQ到SQL绑定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆