以前寫過一個wp8的工程,說實話那會的代碼很麻煩,寫起來費勁,另外還沒多少人下載,不過到windows 10 開始微軟出了UWP架構以後一切都像以前的winform wpf一樣好轉起來,新建一個工程以後模板很簡潔。現在就開始介紹一下基本控制項的使用,為新手寫程式提供一個例子。7天酒店沒有官方客戶端.....
以前寫過一個wp8的工程,說實話那會的代碼很麻煩,寫起來費勁,另外還沒多少人下載,不過到windows 10 開始微軟出了UWP架構以後一切都像以前的winform wpf一樣好轉起來,新建一個工程以後模板很簡潔。
現在就開始介紹一下基本控制項的使用,為新手寫程式提供一個例子。7天酒店沒有官方客戶端,不過不妨礙拿他做例子。
由於以前代碼使用到了json.net 為了減少代碼修改,所以還是需要引入進來,但去官方網站下載的無法直接使用,說什麼不適配,只要打開
然後呢搜索Json 其實我打開預設第二個就是
添加好之後呢
開始佈局代碼
在MainPage.xaml中寫如下代碼
<Page x:Class="_7inns.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:_7inns" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid.Resources> <CollectionViewSource x:Name="itemcollectSource" IsSourceGrouped="true" ItemsPath="ItemContent" /> </Grid.Resources> <Image Source="Assets/2.png" Margin="42,23,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="109" Width="94" /> <TextBlock Margin="42,193,264,0" TextWrapping="Wrap" Text="城市" VerticalAlignment="Top" FontSize="20" FontWeight="Bold"/> <TextBlock Margin="42,252,264,0" TextWrapping="Wrap" Text="區域" VerticalAlignment="Top" FontSize="20" FontWeight="Bold"/> <Button x:Name="buttonCities" Content="" HorizontalAlignment="Stretch" Margin="104,194,3,0" VerticalAlignment="Top" Click="buttonCities_Click" BorderThickness="1" Height="33"/> <SemanticZoom x:Name="semanticZoomCities" Margin="0" ViewChangeCompleted="SemanticZoom_ViewChangeCompleted" Visibility="Collapsed" Canvas.ZIndex="5" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <SemanticZoom.ZoomedInView> <ListView x:Name="ListCities" ScrollViewer.IsHorizontalScrollChainingEnabled="False" ScrollViewer.IsVerticalScrollChainingEnabled="False" ItemClick="ListCities_ItemClick" SelectionChanged="ListCities_SelectionChanged"> <ListView.GroupStyle> <GroupStyle> <GroupStyle.HeaderTemplate> <DataTemplate> <Border Background="#FFECAE0A" Height="60" Width="60"> <TextBlock Text="{Binding Key}" FontSize="50" Foreground="{ThemeResource ApplicationForegroundThemeBrush}"></TextBlock> </Border> </DataTemplate> </GroupStyle.HeaderTemplate> </GroupStyle> </ListView.GroupStyle> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding name}" Height="40" FontSize="30"></TextBlock> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </SemanticZoom.ZoomedInView> <SemanticZoom.ZoomedOutView> <GridView x:Name="GridCitiesFirstName" ScrollViewer.IsHorizontalScrollChainingEnabled="False" ScrollViewer.IsVerticalScrollChainingEnabled="False" Margin="0,100" HorizontalAlignment="Center" VerticalAlignment="Center"> <GridView.ItemTemplate> <DataTemplate> <Border Height="60"> <TextBlock Text="{Binding Group.Key}" FontSize="24"></TextBlock> </Border> </DataTemplate> </GridView.ItemTemplate> <GridView.ItemsPanel> <ItemsPanelTemplate> <WrapGrid ItemWidth="60" ItemHeight="60" VerticalChildrenAlignment="Center" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center" /> </ItemsPanelTemplate> </GridView.ItemsPanel> <GridView.ItemContainerStyle> <Style TargetType="GridViewItem"> <Setter Property="BorderBrush" Value="Gray" /> <Setter Property="Background" Value="#FFECAE0A" /> <Setter Property="BorderThickness" Value="3" /> <Setter Property="HorizontalContentAlignment" Value="Center" /> <Setter Property="VerticalContentAlignment" Value="Center" /> </Style> </GridView.ItemContainerStyle> </GridView> </SemanticZoom.ZoomedOutView> </SemanticZoom> <ComboBox x:Name="comboBoxDistricts" Margin="107,251,0,0" VerticalAlignment="Top" BorderThickness="1" SelectionChanged="comboBoxDistricts_SelectionChanged" Width="251"/> <TextBlock Margin="42,368,264,0" TextWrapping="Wrap" Text="關鍵字" VerticalAlignment="Top" FontSize="20" FontWeight="Bold"/> <TextBlock Margin="42,442,264,0" TextWrapping="Wrap" Text="入住時間" VerticalAlignment="Top" FontSize="20" FontWeight="Bold"/> <Button x:Name="search" Content="搜索" HorizontalAlignment="Right" Margin="0,0,10,49" VerticalAlignment="Bottom" Click="search_Click" FontSize="20" FontWeight="Bold" BorderThickness="1" RenderTransformOrigin="0.925,0.455" Width="129"/> <DatePicker x:Name="inRoomDate" Margin="96,454,0,0" VerticalAlignment="Top" DateChanged="inRoomDate_DateChanged" BorderThickness="1" Width="255"/> <TextBox x:Name="keyword" Margin="104,358,1,0" TextWrapping="Wrap" VerticalAlignment="Top"/> </Grid> </Page>
恕當時沒什麼佈局概念,基本就是手動佈局,羅列控制項。佈局的事情以後再慢慢寫,不過微軟的教程或者其他書裡面這塊講的很清楚,各種panel grid 佈局。
這個裡面基本就是一些textblock 跟textbox button 和一個SemanticZoom SemanticZoom的效果就是聯繫人菜單那個感覺,這裡用來選擇城市
先看一下選擇前的
點一下字母 就會有
然後可以選個北京
後臺呢就會對這個選擇的city進行行政區查詢
private async void ListCities_SelectionChanged(object sender, SelectionChangedEventArgs e) { Debug.WriteLine("ListCities_SelectionChanged"); if (e.AddedItems.Count == 1) { currentCityItem = (CityItem)e.AddedItems.First(); Debug.WriteLine(currentCityItem.name); buttonCities.Content = currentCityItem.name; } string di = await FindDistrict(currentCityItem.id); int total = di.Length; semanticZoomCities.Visibility = Visibility.Collapsed; if (total <= 6) return; JArray jobjectAllDistricts = JArray.Parse(di); comboBoxDistricts.PlaceholderText = ""; comboBoxDistricts.Items.Clear(); if (DItem != null) { DItem.Clear(); for (int i = 0; i < jobjectAllDistricts.Count; i++) { DItem.Add(new DistrictItem { id = (string)jobjectAllDistricts[i]["id"], name = (string)jobjectAllDistricts[i]["name"] }); //Debug.WriteLine((string)jobjectAllDistricts[i]["name"]); comboBoxDistricts.Items.Add((string)jobjectAllDistricts[i]["name"]); } } Debug.WriteLine("Total bytes returned: " + total); }
FindDistrict這個函數就需要用到http請求了
當時這麼寫的 可能是win10推薦的代碼 不過能用
private async Task<string> FindDistrict(string id) { string url = @"http://m.7daysinn.cn/q/city/" + id + @"/districts"; HttpClientHandler handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; HttpClient httpClient = new HttpClient(handler); // Limit the max buffer size for the response so we don't get overwhelmed httpClient.MaxResponseContentBufferSize = 256000; string result; try { result = await httpClient.GetStringAsync(url); return result; } catch (Exception) { } return ""; }
點擊搜索按鈕
就可以得到這個日子的酒店列表啦
private async void search_Click(object sender, RoutedEventArgs e) { try { string url = @"http://m.7daysinn.cn/q/inns?cityId=" + currentCityItem.id; if (currentDistrictItem != null && currentDistrictItem.id != "") { url += "&districtId="; url += currentDistrictItem.id; } if (keyword.Text != "") { url += "&keyword="; url += Uri.EscapeUriString(keyword.Text); } url += "&fromDate=" + inDate.Date.ToString("yy-MM-dd") + "&days=1&getQuota=true"; HttpClientHandler handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; HttpClient httpClient = new HttpClient(handler); // Limit the max buffer size for the response so we don't get overwhelmed httpClient.MaxResponseContentBufferSize = 256000; ParameterObject po = new ParameterObject(); po.result = await httpClient.GetStringAsync(url); po.date = inDate; Frame.Navigate(typeof(InnStatus), po); } catch (Exception) { } }
Frame.Navigate(typeof(InnStatus), po);這句呢就是把數據傳到第二個頁面
第二個頁面Innstatus 解析並且展示出來
protected override void OnNavigatedTo(NavigationEventArgs e) { innstatus = (ParameterObject)e.Parameter; try { List<InnItem> innItems = new List<InnItem>(); JObject jobjectAllInns = JObject.Parse(innstatus.result); JArray jaRooms = (JArray)jobjectAllInns["content"]; for (int i = 0; i < jaRooms.Count; i++) { innItems.Add(new InnItem { innId = (string)jaRooms[i]["innId"], name = (string)jaRooms[i]["name"], firstCharsOfPinyin = (string)jaRooms[i]["firstCharsOfPinyin"], cityId = (string)jaRooms[i]["cityId"], cityName = (string)jaRooms[i]["cityName"], districtId = (string)jaRooms[i]["districtId"], districtName = (string)jaRooms[i]["districtName"], address = (string)jaRooms[i]["address"], score = (string)jaRooms[i]["score"], orderWeight = (string)jaRooms[i]["orderWeight"], thumbnailPath = (string)jaRooms[i]["thumbnailPath"], lowestPrice = (string)jaRooms[i]["lowestPrice"], hasRoom = (string)jaRooms[i]["hasRoom"], hasWifi = (string)jaRooms[i]["hasWifi"], hasPark = (string)jaRooms[i]["hasPark"], canUseCashCoupon = (string)jaRooms[i]["canUseCashCoupon"], brandId = (string)jaRooms[i]["brandId"], //currentActivities = (string)jaRooms[i]["currentActivities"], }); } this.inncollectSource.Source = innItems; ContentInnsList.ItemsSource = inncollectSource.View; } catch (Exception) { } }
效果如下
第二個頁面的xaml代碼就這麼寫的
一個數據模板
<Page x:Class="_7inns.InnStatus" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:_7inns" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid x:Name="LayoutRoot"> <Grid.ChildrenTransitions> <TransitionCollection> <EntranceThemeTransition/> </TransitionCollection> </Grid.ChildrenTransitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!-- TitlePanel --> <StackPanel Grid.Row="0" Margin="0" Orientation="Horizontal"> <TextBlock Text="酒店狀態" Style="{ThemeResource TitleTextBlockStyle}" Typography.Capitals="SmallCaps" Margin="0,15,0,16.5" RenderTransformOrigin="1.473,0.155" Width="300" TextAlignment="Center"/> </StackPanel> <!--TODO: Content should be placed within the following grid--> <Grid Grid.Row="1" x:Name="ContentRoom"> <Grid.Resources> <CollectionViewSource x:Name="inncollectSource" IsSourceGrouped="False" ItemsPath="" /> </Grid.Resources> <ListView x:Name="ContentInnsList" HorizontalAlignment="Left" Margin="0" VerticalAlignment="Top" IsItemClickEnabled="True" ItemClick="ContentInnsList_ItemClick"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding name}" Height="40" FontSize="30"></TextBlock> <TextBlock Text="{Binding address}" Height="30" FontSize="14" Foreground="#FFECAE0A"></TextBlock> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Grid> </Grid> </Page>
好啦 要介紹的就這麼多
工程我上傳上來好了方便新手調試
http://files.cnblogs.com/files/emsoro/7inns.zip