# 應用設置和應用幫助
### ”設置“合約
上一節中我們學習了如何將應用設置保存到本地,這種方式是通過在App內添加設置選項,這里還有一種方式。微軟將其稱為“設置”合約,并且所有的Windows應用商店應用都將自動配合這種合約。但是應用自帶的這種設置如果不做任何修改可謂毫無作用。而我們添加這些設置則可以讓應用更加個性化哦。
### SettingsFlyout
首先新建一個SettingsFlyout頁面,也許很多童鞋會像我當初學這個一樣立馬就調試程序等著看看這個設置是長什么樣,不過現在還用不了哦。
如下所示,我們可以修改IconSource來改變”設置“中的圖標。

然后我將設置界面的布局設置如下咯。
~~~
<StackPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Orientation="Vertical">
<StackPanel Orientation="Vertical" >
<TextBlock Text="Big Car 的美好一天" FontSize="28" Foreground="Red" Margin="12"/>
<TextBlock Text="購買一輛Big Car會讓你的生活充滿活力,充滿激情!" FontSize="20" Margin="12" TextWrapping="Wrap" Foreground="Black"/>
<TextBlock Text="想購買的話可以直接發郵件 nomasp@outlook.com" FontSize="20" Margin="12" Foreground="Gold" TextWrapping="Wrap"/>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="8">
<ToggleSwitch x:Name="toggleSwitch1" Header="每日更新Big Car的最新圖片" OnContent="On" OffContent="Off" Toggled="ToggleSwitch_Toggled" />
<ToggleSwitch x:Name="toggleSwitch2" Header="向我推送相關的動態" OnContent="On" OffContent="Off" Toggled="ToggleSwitch_Toggled" IsOn="True"/>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="0,12,0,12">
<Button Content="好評該應用唄" Margin="12"/>
<Button Content="清除所有緩存" Margin="12"/>
</StackPanel>
</StackPanel>
~~~
### App.xaml.cs
先在app.xaml.cs中添加下面這條命名空間,和以下3個方法
~~~
using Windows.UI.ApplicationSettings;
~~~
~~~
protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
}
private void OnCommandsRequested(SettingsPane sender,SettingsPaneCommandsRequestedEventArgs args)
{
args.Request.ApplicationCommands.Add(new SettingsCommand("BigCarMainSettings", "Big Car 的主要設置", (handler) => ShowCustomSettingFlyout()));
}
public void ShowCustomSettingFlyout()
{
BigCarSettings CustomSettingFlyout = new BigCarSettings();
CustomSettingFlyout.Show();
}
~~~



當然了,在那些控件中的點擊啥的最后都要在后臺代碼中添加的,就像上一篇博客那樣來保存設置就好啦。
以上就是關于應用設置同樣的內容咯,而應用幫助嘛,和這些都是一樣的呀。創建同樣的目標就好了。然后在XAML中修改成自己喜歡的樣子就好啦。而且和應用設置一樣,我們也可以在底部設置應用欄的,關于應用欄的內容可以查看第三章的“應用欄”一節。
~~~
protected override void OnWindowCreated(WindowCreatedEventArgs args)
{
SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;
}
private void OnCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
args.Request.ApplicationCommands.Add(new SettingsCommand("BigCarHelp", "Big Car 的幫助", (handler) => ShowHelpSettingsFlyout()));
}
public void ShowHelpSettingsFlyout()
{
BigCarHelphelpSF = new BigCarHelp();
helpSF.Show();
}
~~~
# 在應用中集成搜索
上一節是關于如何添加應用設置和幫助,這一篇講的是和設置類似的搜索。
So…… Let’s do it !
先從簡單的頁面布局開始,想想我們需要什么,一個帶搜索事件的Button,還需要一些TextBlock來提示用戶,核心部分自然是一個GridView咯。
~~~
<Grid Background="Wheat">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Vertical">
<Button Grid.Row="0" Name="btnSearch" VerticalAlignment="Center" HorizontalAlignment="Left"
Content="搜索" FontFamily="華文行楷" Click="btnSearch_Click" Margin="12" FontSize="34" Foreground="Red"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="搜索關鍵詞" Foreground="Green" FontSize="28" Margin="12"/>
<TextBlock FontSize="28" Foreground="Green" Name="tBlockKeyword" Margin="12"/>
</StackPanel>
</StackPanel>
<GridView Grid.Row="1" Margin="12" x:Name="gridView">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" FontSize="24" Foreground="Pink" FontFamily="楷體"/>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
~~~
既然界面完成了,就該去后臺搗鼓咯。搜索的核心在于SearchPane,所以先來實例化它。為了簡化,我們就將待搜索的內容設置為一串字符串數組好了,當然了,初始化數組的方式大家隨意就好了。
~~~
SearchPane searchPane = null;
string[] exampleStr = new string[100];
public void InitExampleStr()
{
Random ran = new Random();
int exNumber;
for(int i=0;i<100;i++)
{
exNumber = ran.Next(1000, 9999);
exampleStr[i] = exNumber.ToString();
}
}
~~~
當用戶在搜索框中輸入的內容發生了更改時就會觸發searchPane_QueryChange事件。
當用戶在完成輸入后按下Enter鍵或者點擊旁邊的搜索確認按鈕后就會觸發searchPane_QuerySubmitted事件。
~~~
void searchPane_QueryChanged(SearchPane sender, SearchPaneQueryChangedEventArgs args)
{
this.tBlockKeyword.Text = args.QueryText;
}
void searchPane_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
{
string key = args.QueryText;
var result = exampleStr.Where(s => s.Contains(key)).ToArray();
this.gridView.ItemsSource = result;
}
~~~
然后我們還需要這兩個事件在OnNavigatedTo中綁定以及在OnNavigatedFrom中解綁。
~~~
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.searchPane.QuerySubmitted += searchPane_QuerySubmitted;
this.searchPane.QueryChanged += searchPane_QueryChanged;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
this.searchPane.QuerySubmitted -= searchPane_QuerySubmitted;
this.searchPane.QueryChanged -= searchPane_QueryChanged;
}
~~~
然后我們需要點擊Button控件來調出系統的搜索框,一行代碼就足以搞定了。如果不想點擊按鈕也是可以得哦,可以讓用戶直接在鍵盤輸入而調出搜索框呢。
~~~
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
this.searchPane.Show();
}
~~~
~~~
this.searchPane.ShowOnKeyboardInput = true;
~~~
最后別忘了將他們都放到MainPage()中哦,
~~~
public MainPage()
{
this.InitializeComponent();
searchPane = SearchPane.GetForCurrentView();
InitExampleStr();
this.searchPane.PlaceholderText = "請輸入關鍵字";
this.searchPane.ShowOnKeyboardInput = true;
}
~~~
所以說,總的代碼是這樣的。
~~~
SearchPane searchPane = null;
string[] exampleStr = new string[100];
public MainPage()
{
this.InitializeComponent();
searchPane = SearchPane.GetForCurrentView();
InitExampleStr();
this.searchPane.PlaceholderText = "請輸入關鍵字";
this.searchPane.ShowOnKeyboardInput = true;
}
public void InitExampleStr()
{
Random ran = new Random();
int exNumber;
for(int i=0;i<100;i++)
{
exNumber = ran.Next(1000, 9999);
exampleStr[i] = exNumber.ToString();
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.searchPane.QuerySubmitted += searchPane_QuerySubmitted;
this.searchPane.QueryChanged += searchPane_QueryChanged;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
this.searchPane.QuerySubmitted -= searchPane_QuerySubmitted;
this.searchPane.QueryChanged -= searchPane_QueryChanged;
}
void searchPane_QueryChanged(SearchPane sender, SearchPaneQueryChangedEventArgs args)
{
this.tBlockKeyword.Text = args.QueryText;
}
void searchPane_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
{
string key = args.QueryText;
var result = exampleStr.Where(s => s.Contains(key)).ToArray();
this.gridView.ItemsSource = result;
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
this.searchPane.Show();
}
}
~~~
在清單文件中聲明你需要使用“Search”功能后就可以開始調試咯。


大家肯定都用的音樂播放器肯定都會在搜索框下面給出一些建議吧,或者大家常用的地圖等App。
那么我們就對前面的代碼進行更新就好啦。
下面這段代碼呢,就是根據用戶的輸入來顯示建議列表的方法咯。
~~~
void searchPane_SuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs args)
{
var deferralSeg= args.Request.GetDeferral();
var q = from i in exampleStr
where i.Contains(args.QueryText)
select i;
var res = q.Take(suggestionLen).ToArray();
foreach (var item in res)
{
args.Request.SearchSuggestionCollection.AppendQuerySuggestion(item);
}
deferralSeg.Complete();
}
~~~
這篇博客,使用大量LINQ技術,如果不太懂的話可以看看這里。
[【LINQ技術】擴展特性和LINQ操作符](http://blog.csdn.net/nomasp/article/details/45461517):[http://blog.csdn.net/nomasp/article/details/45461517](http://blog.csdn.net/nomasp/article/details/45461517)
使用搜索建議的最大好處在于我們可以選擇并非自己輸入的內容,這個功能就由下面這段代碼提供動力支持。
~~~
void searchPane_ResultSuggestionChosen(SearchPane sender, SearchPaneResultSuggestionChosenEventArgs args)
{
sender.TrySetQueryText(args.Tag);
var q = from t in exampleStr
where t.Contains(args.Tag)
select t;
this.gridView.ItemsSource = q.ToArray();
}
~~~
我們還可以對前面的searchPane_QuerySubmitted函數做如下修改。
~~~
void searchPane_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
{
//var q = from extStr in exampleStr
// where extStr.Contains(args.QueryText)
// select extStr;
//this.gridView.ItemsSource = q.ToArray();
string key = args.QueryText;
var result = exampleStr.Where(s => s.Contains(key)).ToArray();
this.gridView.ItemsSource = result;
}
~~~
最后還需要將他們添加到OnNavigatedTo和OnNavigatedFrom方法中。
~~~
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.searchPane.QuerySubmitted += searchPane_QuerySubmitted;
this.searchPane.QueryChanged += searchPane_QueryChanged;
this.searchPane.SuggestionsRequested += searchPane_SuggestionsRequested;
this.searchPane.ResultSuggestionChosen += searchPane_ResultSuggestionChosen;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
this.searchPane.QuerySubmitted -= searchPane_QuerySubmitted;
this.searchPane.QueryChanged -= searchPane_QueryChanged;
this.searchPane.SuggestionsRequested -= searchPane_SuggestionsRequested;
this.searchPane.ResultSuggestionChosen -= searchPane_ResultSuggestionChosen;
}
~~~
然后調試就會是這個效果咯。

# 使用粘貼板
記得智能手機剛出來那會比較火的一個概念“能夠復制粘貼的手機就是智能手機”。現在看來,這不過是個老掉牙的功能了,但實際用處卻是非常強大的,那么現在我們就來試試怎么做到這個功能。
粘貼板的英文名叫做Clipboard,這也是它的類名了。
新建工程這種就不說了,在XAML中代碼如下:
~~~
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid Margin="12" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="500">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0" Name="btnClip" Margin="0,3,0,16" Content="粘貼" FontSize="32" Click="btnClip_Click" IsEnabled="False"/>
<ScrollViewer Name="scrollView" Grid.Row="1" Visibility="Collapsed">
<TextBlock Margin="12" Name="tBlockClipboard" FontSize="35" Foreground="Gainsboro" TextWrapping="Wrap" />
</ScrollViewer>
</Grid>
</Grid>
~~~
在后臺代碼中寫上這么一個方法:
~~~
void Clipboard_ContentChanged(object sender, object e)
{
DataPackageView pv = Clipboard.GetContent();
if (pv.Contains(StandardDataFormats.Text))
{
btnClip.IsEnabled = true;
}
}
~~~
StandardDataFormats是標準數據格式,這里判斷它是否是Text,如果是的話則讓前面的Button按鈕可用(之前設為不可用,以灰色顯示)。
標準數據格式有Bitmap,HTML,RTF,StorageItems,Text,Uri等。
然后在按鈕的Click事件中寫如下代碼:
~~~
private async void btnClip_Click(object sender, RoutedEventArgs e)
{
var txt = await Clipboard.GetContent().GetTextAsync();
tBlockClipboard.Text = txt;
}
~~~
這里我們使用了Clipboard類的GetContent()方法,用于在剪切板中取出DataPackageView對象數據;類似的還有SetContent(),用于把數據存入剪切板中。還有Clear事件來清空剪切板,Flush事件把數據從源寫入到剪切板,并且在應用程序退出后依然保留在剪切板中。還有ContentChanged事件在剪切板中存儲的數據內容發生變化時自動激活以達到監聽剪切板內容變化的效果。
~~~
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Clipboard.ContentChanged += Clipboard_ContentChanged;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
Clipboard.ContentChanged -= Clipboard_ContentChanged;
}
void Clipboard_ContentChanged(object sender, object e)
{
DataPackageView pv = Clipboard.GetContent();
if (pv.Contains(StandardDataFormats.Text)||pv.Contains(StandardDataFormats.Bitmap))
{
btnClip.IsEnabled = true;
}
}
~~~
大家可以試試,已經完成了,但我們可以做的更多,不是嗎?
完整的代碼如下:
~~~
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid Margin="12" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Height="500">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0" Name="btnClip" Margin="0,3,0,16" Content="粘貼" FontSize="32" Click="btnClip_Click" IsEnabled="False"/>
<ScrollViewer Name="scrollView" Grid.Row="1" Visibility="Collapsed">
<TextBlock Margin="12" Name="tBlockClipboard" FontSize="35" Foreground="Gainsboro" TextWrapping="Wrap" />
</ScrollViewer>
<Image x:Name="imgClicpboard" Grid.Row="1" Margin="5" Stretch="Uniform" Visibility="Collapsed"/>
</Grid>
</Grid>
~~~
~~~
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Clipboard.ContentChanged += Clipboard_ContentChanged;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
Clipboard.ContentChanged -= Clipboard_ContentChanged;
}
void Clipboard_ContentChanged(object sender, object e)
{
DataPackageView pv = Clipboard.GetContent();
if (pv.Contains(StandardDataFormats.Text)||pv.Contains(StandardDataFormats.Bitmap))
{
btnClip.IsEnabled = true;
}
}
private async void btnClip_Click(object sender, RoutedEventArgs e)
{
scrollView.Visibility = Visibility.Collapsed;
imgClicpboard.Visibility = Visibility.Collapsed;
tBlockClipboard.Text = " ";
imgClicpboard.Source = null;
DataPackageView pv = Clipboard.GetContent();
if (pv.Contains(StandardDataFormats.Text))
{
scrollView.Visibility = Visibility;
var txt = await Clipboard.GetContent().GetTextAsync();
tBlockClipboard.Text = txt;
}
else if(pv.Contains(StandardDataFormats.Bitmap))
{
imgClicpboard.Visibility = Visibility;
var bmp = await Clipboard.GetContent().GetBitmapAsync();
Windows.UI.Xaml.Media.Imaging.BitmapImage bitMap = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
bitMap.SetSource(await bmp.OpenReadAsync());
this.imgClicpboard.Source = bitMap;
}
}
}
~~~
現在它還可以復制圖片了哦~

# 設置共享(共享源和共享目標)
上一節簡單介紹了通過粘貼板來共享數據,這一節將會添加更為強大的功能哦。
以下就是大概的樣式了,隨便看看就好了,這都不是重點。
~~~
<Grid Background="AliceBlue">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition />
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" FontSize="25" Foreground="Red" Text="共享源示例" Margin="12"/>
<ScrollViewer Grid.Row="1" Margin="14" VerticalScrollMode="Auto" HorizontalScrollMode="Disabled">
<StackPanel>
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="radioBtnText" Foreground="Aqua" FontWeight="Bold" FontSize="22" Content="共享文本" Checked="OnChecked" GroupName="g" Tag="text"/>
<RadioButton x:Name="radioBtnImg" Foreground="Aqua" FontWeight="Bold" FontSize="22" Content="共享圖像" Margin="12,0,0,0" Checked="OnChecked" GroupName="g" Tag="image"/>
<RadioButton x:Name="radioBtnFile" Foreground="Aqua" FontWeight="Bold" FontSize="22" Content="共享文件" Margin="12,0,0,0" Checked="OnChecked" GroupName="g" Tag="file"/>
</StackPanel>
<StackPanel Name="stackPText" Visibility="Collapsed" Margin="8">
<TextBlock Text="共享文本" FontSize="25"/>
<TextBlock Foreground="Gold" FontSize="25" Text="輸入要共享的內容" />
<TextBox x:Name="tBlockText" Foreground="Gold" />
</StackPanel>
<StackPanel Name="stackPImg" Visibility="Collapsed" Margin="8">
<TextBlock Text="共享圖像" FontSize="25"/>
<TextBlock Foreground="Gold" FontSize="25" Text="共享以下圖片"/>
<Image Width="600" Height="400" Stretch="UniformToFill" HorizontalAlignment="Left"
Margin="1,5,0,5" Source="Assets/SpaceNeedle1.jpg"/>
</StackPanel>
<StackPanel Name="stackPFile" Visibility="Collapsed" Margin="8">
<TextBlock Text="共享文件" FontSize="28"/>
<TextBlock Foreground="Gold" FontSize="25" Text="選擇要共享的文件"/>
<StackPanel>
<Button Content="選擇文件" Click="OnPickFile"/>
<TextBlock x:Name="tBlockFile" Foreground="Gold" FontSize="24"/>
</StackPanel>
</StackPanel>
</StackPanel>
</ScrollViewer>
<Button Grid.Row="2" Name="btnShare" Margin="12" Content="確定共享" FontSize="35" FontFamily="隸書" Foreground="Azure" Background="Black" Click="btnShare_Click"/>
</Grid>
~~~
這里通過3個StackPanel的“顯示“與”隱藏“來達到在一個位置顯示3個界面的功能,然后在后臺通過以下方法更改Visibility屬性。
~~~
private void OnChecked(object sender, RoutedEventArgs e)
{
RadioButton rbtn = sender as RadioButton;
if (rbtn != null)
{
string tag = rbtn.Tag.ToString();
switch (tag)
{
case "text":
this.stackPText.Visibility = Windows.UI.Xaml.Visibility.Visible;
this.stackPImg.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
this.stackPFile.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
break;
case "image":
this.stackPText.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
this.stackPImg.Visibility = Windows.UI.Xaml.Visibility.Visible;
this.stackPFile.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
break;
case "file":
this.stackPText.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
this.stackPImg.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
this.stackPFile.Visibility = Windows.UI.Xaml.Visibility.Visible;
break;
default:
this.stackPText.Visibility = Windows.UI.Xaml.Visibility.Visible;
this.stackPImg.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
this.stackPFile.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
break;
}
}
}
~~~
以下是核心代碼,通過RadioButton的選擇來共享不同的內容。這里沒有進行try、catch異常檢測,但在實際工程中則是必要的,因為如果你不共享任何內容而點擊共享按鈕你就知道了……
~~~
void MainPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
if (radioBtnText.IsChecked == true)
{
args.Request.Data.Properties.Title = "共享文本";
args.Request.Data.Properties.Description = "共享你輸入的文本數據。";
args.Request.Data.SetText(this.tBlockText.Text);
}
else if (radioBtnImg.IsChecked == true)
{
args.Request.Data.Properties.Title = "共享圖像";
args.Request.Data.Properties.Description = "共享以下圖片。";
args.Request.Data.SetBitmap(Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/SpaceNeedle1.jpg")));
}
else if (radioBtnFile.IsChecked == true)
{
args.Request.Data.Properties.Title = "共享文件";
args.Request.Data.Properties.Description = "共享你選擇的文件。";
var file = this.tBlockFile.Tag as Windows.Storage.StorageFile;
List<IStorageItem> files = new List<IStorageItem>();
files.Add(file);
args.Request.Data.SetStorageItems(files);
}
deferral.Complete();
}
~~~
選擇文件的方法我們在前面也都介紹過了,直接貼代碼……
~~~
private async void OnPickFile(object sender, RoutedEventArgs e)
{
Windows.Storage.Pickers.FileOpenPicker picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.FileTypeFilter.Add(".mp3");
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".docx");
picker.FileTypeFilter.Add(".pptx");
picker.FileTypeFilter.Add(".txt");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
this.tBlockFile.Text = file.Path;
this.tBlockFile.Tag = file;
}
}
~~~
當然了,記得下面這些操作……
~~~
protected override void OnNavigatedTo(NavigationEventArgs e)
{
DataTransferManager.GetForCurrentView().DataRequested += MainPage_DataRequested;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
DataTransferManager.GetForCurrentView().DataRequested -= MainPage_DataRequested;
}
~~~
最后就是共享確認按鈕了,一行代碼搞定。
~~~
private void btnShare_Click(object sender, RoutedEventArgs e)
{
DataTransferManager.ShowShareUI();
}
~~~
以上這個App,你將需要共享的數據從這里發出,也叫共享源,但共享到哪里了呢?

看到”共享圖像“和”共享以下圖片“想起來剛才的兩行代碼了么?這兩個屬性就用在了這里。
~~~
args.Request.Data.Properties.Title = "共享文本";
args.Request.Data.Properties.Description = "共享你輸入的文本數據。";
~~~
我們當然可以將數據共享到郵件、OneNote里,但如果你是要寫一個自己的接收共享數據的應用呢,如何來寫?
接下來就來寫另一個App咯,也就是上圖中的App49了。首先在清單文件中做如下操作,當然了,具體要添加哪些東西大家自己看著辦就好了。


然后添加一個XAML頁面來接收數據,因為你不可能只讓你的APP專門用來接收數據咯,所以就不建議在MainPage中寫了。
在新頁面中大概做一下頁面布局,我的布局通常來說都不是很美觀的……
~~~
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<Grid x:Name="gridText" Margin="24" Visibility="Collapsed" Grid.Row="0">
<StackPanel>
<TextBlock FontSize="25" Foreground="Red" Text="接收到的文本:"/>
<TextBlock FontSize="30" Foreground="Pink" FontWeight="Bold" x:Name="tbText" Margin="8"/>
</StackPanel>
</Grid>
<Grid x:Name="gridImg" Margin="25" Visibility="Collapsed" Grid.Row="0">
<StackPanel>
<TextBlock FontSize="25" Foreground="Red" Text="接收到的圖像:"/>
<Image x:Name="img" Margin="12" Width="500" Height="400" HorizontalAlignment="Left" Stretch="Uniform"/>
</StackPanel>
</Grid>
<Grid x:Name="gridStorageItems" Margin="25" Visibility="Collapsed" Grid.Row="0">
<StackPanel>
<TextBlock FontSize="25" Foreground="Red" Text="接收到的文件:"/>
<TextBlock FontSize="30" Margin="12" x:Name="tbStorageItem"/>
</StackPanel>
</Grid>
<Button Grid.Row="1" HorizontalAlignment="Center" Margin="0,15,0,20"
Content="完成共享" FontSize="28" Width="200" Click="btnCompleteShare_Click"/>
</Grid>
~~~
后臺代碼中寫以下代碼,核心在于if中的3個判斷,就是3中共享的文件了咯。
~~~
public sealed partial class ShareTargetPage : Page
{
ShareOperation shareOperation = null;
public ShareTargetPage()
{
this.InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
ShareOperation sp = e.Parameter as ShareOperation;
if (sp != null)
{
this.shareOperation = sp;
DataPackageView pack = sp.Data;
if (pack.Contains(StandardDataFormats.Text))
{
string s = await pack.GetTextAsync();
this.tbText.Text = s;
this.gridText.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
else if (pack.Contains(StandardDataFormats.Bitmap))
{
var stream = await pack.GetBitmapAsync();
BitmapImage bmp = new BitmapImage();
bmp.SetSource(await stream.OpenReadAsync());
this.img.Source = bmp;
this.gridImg.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
else if (pack.Contains(StandardDataFormats.StorageItems))
{
var storageItems = await pack.GetStorageItemsAsync();
StorageFile file = storageItems[0] as StorageFile;
this.tbStorageItem.Text = file.Name;
this.gridStorageItems.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
}
}
private void btnCompleteShare_Click(object sender, RoutedEventArgs e)
{
this.shareOperation.ReportCompleted();
}
}
~~~
接著我們就要來調試這兩個程序啦。只需要將接受共享數據的App按F5運行后關掉就好了,因為它會部署到本地的,或者也可以在Build選項卡中直接部署也是一樣的。然后按F5運行共享數據的數據源App就好啦。
截圖如下:

這張圖片我壓縮過了,不如太大上傳不了,所以可能看不清楚吧。下面是共享文本數據的過程截圖啦。



這個是共享圖像的截圖,忘了說了,在前面的SpaceNeedle1.jpg就是下面這張圖片我已經事先添加到工程里了的。

緊接著我們共享這個docx文件,卻發現在共享欄里沒有了App49,發生了什么?


下面這首剛才添加的受支持的文件類型,明顯沒有添加.docx,所以這也是一個需要注意的地方。

而想知道如何算出10000的階層可以看[“100的階層真的算不出來嗎?”](http://blog.csdn.net/nomasp/article/details/45484979) :[http://blog.csdn.net/nomasp/article/details/45484979](http://blog.csdn.net/nomasp/article/details/45484979)