Эта статья является 5-м днем в серии под названием « 31 день Windows 8» . Каждая из статей этой серии будет опубликована как для HTML5 / JS, так и для XAML / C # . Вы можете найти все ресурсы, инструменты и исходный код на нашем веб-сайте .
Сегодня мы начинаем серию постов, посвященных контрактам, начиная с настроек приложения. Вероятность того, что они есть в вашем приложении, высока, и вы знаете, что ненавидите их. Для меня они всегда были той вещью, с которой мы только что имели дело, без действительно отличного способа справиться с ними, до сих пор. Настройки приложения — это только часть чего-то большего в Windows 8, называемая контрактами. Давайте начнем наш разговор о настройках с определения контрактов Microsoft:
Контракты Контракт похож на соглашение между одним или несколькими приложениями. Контракты определяют требования, которым должны соответствовать приложения, чтобы участвовать в этих уникальных взаимодействиях Windows.
Например, Windows позволяет пользователям обмениваться контентом из одного приложения в другое. Приложение, которое совместно использует контент, поддерживает исходный контракт, выполняя определенные требования, в то время как приложение, которое получает общий контент, поддерживает целевой контракт, выполняя другой набор требований. Ни одному приложению не нужно ничего знать о другом. Каждое приложение, которое участвует в договоре о совместном использовании, может быть уверенным в том, что рабочий процесс совместного использования полностью поддерживается, сквозной, Windows.
через: http://msdn.microsoft.com/en-us/library/windows/apps/hh464906.aspx
Интересно, что это действительно звучит как «управляемый интерфейс» между приложением и операционной системой Windows. Для наших приложений доступно 5 контрактов:
- Выбор файлов
- Играть
- Поиск
- настройки
- Поделиться
Точно так же, как типичный интерфейс программирования, это означает, что тот, кто расширяет его, использует какой-то тип функциональности, а другой фактически не знает об этом.
В Windows 8 все это выглядит так, как будто это происходит на уровне взаимодействия с пользователем. Что я имею в виду? Что ж, давайте возьмем в качестве примера контракт на акции. Проще говоря, приложения сообщают операционной системе, на что они хотели бы подписаться. В случае обмена, возможно, это принятие изображения или обмена изображением. Windows тогда будет брокером остального.
Imagine a scenario where you find a great article while browsing the web in something like Internet Explorer. You want to share it to someone either in email or Twitter. Assuming you had an application installed that does email or Twitter, and they accepted sharing of an a URI, then Internet Explore could share to those. Better yet, those applications don’t even have to be running to do so. Windows takes care of making all that awesomesauce happen.
Sounds like an typical programming interface doesn’t it.
Defining Settings
The Settings Contract is really just one control, aka the Setting Flyout or WinJS.UI.SettingsFlyout which you will find in the WinJS library. Any application installed from the Microsoft Store will always have two default entry in the Settings Contract; Rate and Review, and Permissions. These are provided by the overall system and not something you will find in the template.
To activate our application settings we need to bring up the Charms menu and selected settings. You can do this a variety of ways, swipe in from the side ( left or right depending on your language ), Windows Key + C, or top \ bottom right hand side of the screen. Once activated select Settings at which point the settings flyout will be appear to float out from the side of the screen. Below is the settings flyout for the Microsoft Store and you can see there are multiple entry points for the store.
The first place to start with creating our own application settings is to tell Windows what in fact our entry points are going to be. We do that when our app starts up for the first time in an event called onsettings. Below I am going to register two different entry points, “about” and “help.»
WinJS.Application.onsettings = function (e) { e.detail.applicationcommands = { "about": { href: "/pages/settings/aboutflyout.html", title: "About" }, "help": { href: "/pages/settings/helpFlyout.html", title: "Help" } } WinJS.UI.SettingsFlyout.populateSettings(e); };
An application can currently have 7 entry points, which will be alphabetically sorted by the property name you’ve created in the object. In our case, “about” and “help”, not the title.
With just our entry points created you can actually run your application and see these listed in the Settings Charm. Of course clicking them, will lead you to an error of resource not found. Let’s add our html pages that match the href’s we’ve already defined.
The Setting(s) UI
With our html pages added, now we have to actually create our user interface. Before you start creating those angle brackets, check out the Windows application settings guidance.
I mentioned earlier that our settings was really just a control called the Settings Flyout. To create our most basic settings page we just need a valid page, an element with an id id=”[name here]“ as well as the settings flyout data-win-control=”WinJS.UI.SettingsFlyout” as seen below.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> </head> <body> <div id="help" data-win-control="WinJS.UI.SettingsFlyout"> <span style="color: black;">Hi.</span> </div> </body> </html>
With this in place we can now navigate to that entry point and see Hi in the top left hand side. Useful but useless. Clearly our next step is to add some meat and potatoes to our page. Below we’re going to:
- Set the controls width to narrow. Two choices, narrow or wide.
- Add a header including a back button to get the user back to the Settings Flyout.
- Add some content.
- And lastly add some CSS to pretty up a few things.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>help</title> <link href="/pages/settings/settings.css" rel="stylesheet" /> </head> <body> <div id="help" class="win-ui-light win-header appSettings" data-win-control="WinJS.UI.SettingsFlyout" data-win-options="{width:'narrow'}"> <div class="SettingsPane"> <div class="win-label"> <button onclick="WinJS.UI.SettingsFlyout.show()" class="win-backbutton"> </button> <span class="SettingsTitle">Help Day #5</span> </div> <article class="SettingsContent"> <div>Hi</div> </article> </div> </div> </body> </html>
That looks a bit more like what a user might expect.
Getting Data
Now settings are all about “setting” something right. That of course means the user is going to do something in that settings page, maybe enter some account information, flip some switches or just personalize a theme. With our modern interface things like unnecessary buttons we need to get rid of, yet we still need to get at that data right. Thankfully there are a number of events which fire around the Settings Flyout, specifically:
- onafterhide – Raised immediately after the SettingsFlyoutis completely hidden.
- onaftershow – Raised immediately after a SettingsFlyoutis fully shown.
- onbeforehide – Raised just before hiding a SettingsFlyout.
- onbeforeshow – Raised just before showing a SettingsFlyout
To walk the pipes a bit. Let’s add a simple input box to our settings UI.
.... <input id="bacon" type="text" value="Bacon is Yummy" /> ....
Since we’re not going to add a button to our UI to “submit” the data somewhere, we need to hand the event afterhide. Here we’re going to attach to that event wiring up our afterSettingHide function.
.... ready: function (element, options) { document.getElementById("about").addEventListener( "afterhide", afterSettingsHide, false); }, unload: function () { document.getElementById("about").removeEventListener( "afterhide", afterSettingsHide); } ....
For brevity sake, the afterSettingsHide function will just dump the input box’s value to the console.
function afterSettingsHide() { console.log(document.getElementById("bacon").value); };
Almost Finished
Having a consistent setting user experience is awesome but there is really one last thing you should do for your users, roam their settings. I know this is going to sound crazy, but there are users out there who have multiple machines. We may not want them to configure your app for every machine they use it on. I know as a user, I sure hate it. We will talk more about storage in another post to come.
Summary
When I was first introduced to Windows 8 I kept hearing the phrase, “Win as 1”. Win as 1 is one of the core tenants for Windows. At first this just sounds like standard marketing speak but actually it’s really far from that. Having now worked with Windows 8 for some time, the contract are a great proof point of this tenant. Things like application settings are now a centralized for the user, our applications can now spend more time focusing on delivering their core features rather than dealing with things like settings. Furthermore, now that the settings are consistent across all applications, we only ever have to teach a user once to use settings across all applications.
“I only had to be taught how to open a door once and then I could open all doors.” – I made that up.
Today, we took a look the Settings Contract, which is just one of many contracts you will find in Windows 8. Just like a programming interface, contracts in Windows 8 offer your app a unique way to extend your application beyond the traditional definition of an “application process” while providing a consistent user interface to our users.
You can download the entire sample solution and tools below.
Tomorrow, we’re going to look at the Search contract. Search is something We’ll dive head first into that tomorrow.
See you then!