UWP下制作简单时间轴控件

0x00.相关

0x01.声明类

    class Html_TimeLineClass
    {
        public string Content { get; set; }
        public string DateTime { get; set; }
        public string Id { get; set; }
        public int Index { get; set; }
    }

0x02.自定义模板

        <DataTemplate x:Key="RightTimeLineItemTemplate">
            <ListViewItem>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*"/>
                        <ColumnDefinition Width="14"/>
                        <ColumnDefinition Width="1*"/>
                    </Grid.ColumnDefinitions >
                    <Border Height="14" Width="14"
                                CornerRadius="6" BorderThickness="2" 
                                BorderBrush="LightGray"
                                Grid.Column="1" VerticalAlignment="Bottom">
                        <Border.Background>
                            <AcrylicBrush 
                                BackgroundSource="HostBackdrop" TintColor="{ThemeResource SystemChromeMediumColor}" TintOpacity=".7"/>
                        </Border.Background >
                    </Border >
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" 
                                Grid.Column="2">
                        <StackPanel Orientation="Vertical">
                            <StackPanel Orientation="Horizontal">
                                <HyperlinkButton Content="{Binding Id}"/>
                                <TextBlock Text="{Binding DateTime}" Margin="8,0,0,0" Foreground="Gray" VerticalAlignment="Center"/>
                            </StackPanel >
                            <TextBlock Text="{Binding Content}"/>
                            <Border Height="1" Background="LightGray" CornerRadius="2"/>
                        </StackPanel >
                    </StackPanel>
                </Grid >
            </ListViewItem >
        </DataTemplate >
        <DataTemplate x:Key="LeftTimeLineItemTemplate">
            <ListViewItem>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="1*"/>
                        <ColumnDefinition Width="14"/>
                        <ColumnDefinition Width="1*"/>
                    </Grid.ColumnDefinitions >
                    <Border Height="14" Width="14"
                                CornerRadius="6" BorderThickness="2" 
                                BorderBrush="LightGray"
                                Grid.Column="1" VerticalAlignment="Bottom">
                        <Border.Background>
                            <AcrylicBrush 
                                BackgroundSource="HostBackdrop" TintColor="{ThemeResource SystemChromeMediumColor}" TintOpacity=".7"/>
                        </Border.Background >
                    </Border >
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" 
                                Grid.Column="0" >
                        <StackPanel Orientation="Vertical">
                            <StackPanel Orientation="Horizontal">
                                <HyperlinkButton Content="{Binding Id}"/>
                                <TextBlock Text="{Binding DateTime}" Margin="8,0,0,0" Foreground="Gray" VerticalAlignment="Center"/>
                            </StackPanel >
                            <TextBlock Text="{Binding Content}"/>
                            <Border Height="1" Background="LightGray" CornerRadius="2"/>
                        </StackPanel >
                    </StackPanel>
                </Grid >
            </ListViewItem >
        </DataTemplate >

0x03.自定义模板选择器

XAML

        <local:TimeLineItemTemplateSelector
            x:Key="TimeLineItemTemplateSelector"
            LeftTimeLineItemTemplate="{StaticResource LeftTimeLineItemTemplate}"
            RightTimeLineItemTemplate="{StaticResource RightTimeLineItemTemplate}" />

C#

    public class TimeLineItemTemplateSelector : DataTemplateSelector
    {
        public DataTemplate LeftTimeLineItemTemplate { get; set; }
        public DataTemplate RightTimeLineItemTemplate { get; set; }
        protected override DataTemplate SelectTemplateCore(object item)
        {
            int index= ((Html_TimeLineClass)item).Index;
            if (index % 2 == 1)
                return RightTimeLineItemTemplate;
            else return LeftTimeLineItemTemplate;
        }//奇按照偶性左右分布
    }

0x04.绘制中轴和Listview容器

                <Grid>
                    <Border HorizontalAlignment="Center" Width="3" Background="Gray"
                        CornerRadius="2" Margin="0,10,0,10"/>
                    <ListView x:Name="TimeLineListview" Margin="0,10,0,10"
                               SelectionMode="None"
                               ItemContainerStyle="{StaticResource LVCstretch}" 
                               ItemTemplateSelector="{StaticResource TimeLineItemTemplateSelector}"
                               IsItemClickEnabled="True">
                    </ListView >
                </Grid >

0x05.数据绑定

TimeLineListview.ItemsSource = your datasource;

0x06.效果图

【UWP】跨页面访问控件

为需要跨页面访问的控件于XAML添加下列代码:

x:FieldModifier=" Public"
<Frame x:FieldModifier=" Public" x:name="primaryFrame"/>
public sealed partial class MainPage : 
Page 
{ 
  public static MainPage firstPage; 
  public MainPage() 
    { 
      this.InitializeComponent(); 
      firstPage= this; 
    }
}    

其他页面引用代码:

MainPage.firstPage.primaryFrame

C#使用Xpath进行html解析

0x00.Xpath

XPath 使用路径表达式来选取 XML 文档中的节点或者节点集。这些路径表达式和我们在常规的电脑文件系统中看到的表达式非常相似。

XPath 含有超过 100 个内建的函数。这些函数用于字符串值、数值、日期和时间比较、节点和 QName 处理、序列处理、逻辑值等等。


0x01.添加引用

Nuget中下载 HtmlAgilityPack,项目中引用

using HtmlAgilityPack;

0x02.Load html页面

HtmlDocument index = web.Load("http://www.sonystyle.com.cn/mysony/acafe/index.htm");

0x03.查看所需元素的Xpath

浏览器以火狐为例

打开所需网页,F12进入控制台

定位到所需元素,右键→复制→Xpath

e.g:/html/body/div[3]/div[1]/div/div/div[1]/div[1]/div[1]


0x04.DocumentNode.SelectNodes的用法

DocumentNode.SelectNodes选择的是多个节点,需要使用集合

private List<string>list;

foreach (var sth in index.DocumentNode.SelectNodes("//ul[@class='slides']/li/a/img"))
{
  list.Add(base_url + index_img.GetAttributeValue("src", ""));//获取对应元素的src值
}

//*是固定格式,*表示匹配中的元素
/ 表示下一次
@表示对应的属性,如//ul[@class=’slides’]表示class为slides的ul元素


0x05.DocumentNode.SelectNodes的用法

DocumentNode.SelectNodes选择的是单一元素,所以需要使用该元素的绝对路径

var sth = index.DocumentNode.SelectSingleNode("//div/li/a/img");
var attribute=sth.GetAttributeValue("src", ""));

0x06.更多

Xpath参考手册

UWP模拟获取验证码

0x00.添加引用

using System.Threading.Tasks;
using System.Net.Http;

0x01.创建新Task

public static Task<HttpResponseMessage> VerCode(string Req)//Req为获取验证码的请求连接,可去需要的网站分析请求获取
{
    return Task.Run(() =>
    {
        HttpClient request = new HttpClient(HttpClientHandler);
        HttpResponseMessage response;
        {
            request.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
            request.DefaultRequestHeaders.Add("Accept", "*/*");
            request.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
            request.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
        }//模拟请求头
        try
        {
            response = request.GetAsync(Req).Result;//响应内容为MIME
        }
        catch
        {
            response = null;
        }
        return response;
    });
}

0x02.流形式读取

private async Task GetVerCodeAsync(string Req)//Req为获取验证码的请求连接,可去需要的网站分析请求获取
{
    HttpResponseMessage response = await Sign.VerCode(Req);
    byte[] streamByte = response.Content.ReadAsByteArrayAsync().Result;
    MemoryStream ms = new MemoryStream(streamByte);
    BitmapImage img = new BitmapImage();
    await img.SetSourceAsync(ms.AsRandomAccessStream());//img为Image控件
    VerCodeImg.Source = img;
}

0x03.点击刷新(因网站而异)

private async void VerCodeBtn_Click(object sender, RoutedEventArgs e)
{
    a = a + 1;
    string plus = "?test=" + a;
    string baseReq = "https://www.sonystyle.com.cn/mysony/campaign/api/captcha.do" + plus;
    await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
    {
        await GetVerCodeAsync(baseReq);
    });
}

0x04.相关

MIME 参考手册

UWP标题栏扩展

0x00.添加引用

在默认引用下添加

using Windows.ApplicationModel.Core

0x01.实现

public MainPage()
{
  this.InitiallizeComponent();
  var titlebar=CoreApplication.GetCurrentView().TitleBar;
  titlebar.ExtendViewIntoTitleBar=true;
  Window.Current.SetTitleBar(thingsuneed);//thingsuneed 为需要扩展至标题栏的控件的X:name
}

 

 

UWP控件Navigationview

0x00.规范布局

微软通过秋季更新发布了 NavigationView 控件。在此之前,实现汉堡菜单多使用Nuget上发布的类库或使用Splitview自制,但无法保持风格的一致性。

MSDN给出的实例

<NavigationView SelectionChanged="SelectionChanged">
  <NavigationView.MenuItems>
    <NavigationViewItemHeader Content="Section A" />
    <NavigationViewItem Content="Item 01" />
    <NavigationViewItem Content="Item 02" />
  </NavigationView.MenuItems>
  <Frame x:Name="NavigationFrame" />
</NavigationView>

0x01.模式

控件有三种可能的模式:最小、紧凑和扩展,每种模式都是基于带有阈值的内置和可自定义视图自动选择的。


0x02.NavigationViewItem

NavigationViewItem为NavigationView.MenuItems中item项,包含Icon,Content,Tag等常用属性。

Icon:参阅Segoe MDL2 icons提供的图标。

IsSelected:NavigationViewItem是否被选中,选中的NavigationViewItem左侧会有指示方块。如果出现默认需要选中的NavigationViewItem没有指示方块并且已设置IsSelected=true

请为NavigationViewItem添加Loading事件即可正常显示。

private void NavigationViewItem_Loading(Windows.UI.Xaml.FrameworkElement sender, object args)
{
    ((NavigationViewItem)sender).IsSelected = true;
}

0x03.NavigationViewItemSeparator

用于分隔两个NavigationViewItem。


0x04.IsSettingsVisible

Pane底部的Setting按钮是否可见。


0x05.IsPaneOpen

Pane是否展开。


0x06.SelectionChanged事件

当NavigationView中选中的NavigationViewItem改变时触发,常配合Frame控件实现导航视图。

<NavigationView x:Name="NaviView" 
                SelectionChanged="NaviView_SelectionChanged">
    <NavigationView.MenuItems>
        <NavigationViewItem Icon="Home" Content="首页" Tag="Index"/>
        <NavigationViewItem Icon="BrowsePhotos" Content="搜索" Tag="Filter" />
    </NavigationView.MenuItems >

    <Frame x:Name="RootFrame">
      <Frame.ContentTransitions>
        <TransitionCollection>
          <NavigationThemeTransition/>
        </TransitionCollection>
      </Frame.ContentTransitions>
    </Frame >
</NavigationView >
private void NaviView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
        NavigationViewItem item = args.SelectedItem as NavigationViewItem;
        switch (item.Tag)
        {
            case "Index":
                RootFrame.Navigate(typeof(Pages.Index_Page));
            break;

            case "Filter":
                RootFrame.Navigate(typeof(Pages.Filter_Page));
            break;

            case "Setting": 
                RootFrame.Navigate(typeof(Pages.Setting_Page)); 
            break;
        }
}

 

UWP 使用BackgroundTransfer下载图片

 0x00.添加引用

using System;
using System.Threading.Tasks;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;

0x01.下载

Uri uri = new Uri(imageUri);//需要下载图片的Uri,exp:http*****.jpg
BackgroundDownloader backgroundDownload = new BackgroundDownloader();
StorageFolder folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("Acafe", CreationCollisionOption.OpenIfExists);//此处为下载路径,可是要Openfolder改为自定义路径
StorageFile newFile = await folder.CreateFileAsync(imageName, CreationCollisionOption.OpenIfExists);//创建文件,需要定义文件名
DownloadOperation download = backgroundDownload.CreateDownload(uri, newFile);//创建下载器
await download.StartAsync();//启动

 

UWP 自定义Popup控件的自适应

0x00.前提

自定义了一个查看图片细节的控件,本质是一个Image控件,但是应为采用了左侧为NavigationView右侧为Frame的导航模式,为了使该控件能覆盖到左侧的NavigationView之上,只能采用Popup。

这也导致该控件的容器不能是Frame/Page中的Grid,从而不能直接随窗体一起拉伸,可以采用SizeChanged事件和INotifyPropertyChanged接口来实现,也可使使用MeasurePopupSize()


0x01.实现

public Image_Detail()
{
    this.InitializeComponent();
    _popup = new Popup();
    ApplicationView.GetForCurrentView().VisibleBoundsChanged += (s, e) =>
    {
        MeasurePopupSize();
    };
    MeasurePopupSize();
    _popup.Child = this;
}

private void MeasurePopupSize()
{
    this.Width = ApplicationView.GetForCurrentView().VisibleBounds.Width;
    this.Height = ApplicationView.GetForCurrentView().VisibleBounds.Height;
}

UWP 设定图片为桌面/锁屏

0x00.添加引用

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;
using Windows.Storage;
using System;
using Windows.System.UserProfile;
using Windows.ApplicationModel;
using System.Collections.ObjectModel;
using Windows.UI.Xaml.Media;

0x01.选择图片

FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");

var file = await openPicker.PickSingleFileAsync();

0x02.复制所选图片并设定

if (!UserProfilePersonalizationSettings.IsSupported())
{
    MessageDialog md = new MessageDialog("Not Support");
    md.ShowAsync();
}
else
{
    StorageFolder base_folder = await Package.Current.InstalledLocation.GetFolderAsync("Assets");//选择App安装目录下Assets文件夹作为复制目录
    await file.CopyAsync(base_folder,file.Name, NameCollisionOption.ReplaceExisting);//将选择的图片复制到base_folder
    StorageFile copy_file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/" + file.Name));

    UserProfilePersonalizationSettings setting = UserProfilePersonalizationSettings.Current;
    await setting.TrySetWallpaperImageAsync(copy_file);//设置为壁纸,返回true成功,false失败
    await setting.TrySetLockScreenImageAsync(copy_file);//设置为锁屏,返回true成功,false失败
}

PS.如不将所选文件复制至App目录下会出现权限问题

Jumony.Core爬虫学习 [1]

 0x00.Nuget 中下载 Jumony.Core 安装至当前项目

0x01.获取http://www.sonystyle.com.cn/mysony/acafe/index.htm 首页滚动图片URL

foreach (var img in new JumonyParser().LoadDocument("http://www.sonystyle.com.cn/mysony/acafe/index.htm/",Encoding.GetEncoding(65001)).Find("[target=_blank]>img[src*=\"index\"]"))<br> textBox.Text = textBox .Text + "http://www.sonystyle.com.cn/mysony/acafe/" + img.Attribute("src").Value() +" \n";

 

PS. 注意head 中页面的编码信息注意转码

CSS选择器 http://www.w3school.com.cn/cssref/css_selectors.asp