Showing posts with label XAML. Show all posts
Showing posts with label XAML. Show all posts

Monday, September 9, 2013

Value Converter to Binding in Windows Store Apps Using XAML


Introduction of IValueConverter Interface.

IValueConverter is an interface that is use to create a custom converter class by deriving from this interface. Basically IValueConverter has two methods:

  1. Convert: This method is used to create a One-way data binding to a UI element by converting its value. If you implement one-way binding to a target element, then you have to use the Convert Method. In other words when data is passed from the source, the binding engine calls Convert.
  2. ConvertBack: This method is used when you bind the data to a target element using Two-way binding. In the other words you can say that when data is passed from the target, the binding engine calls ConvertBack and passes the returned data to the source.
Once a value converter is created, you can select the value converter in the XAML Designer when you configure a data binding.

Let's see an example to understand it better.

Follow these steps..

Step 1

Create a blank Windows Store apps application using XAML and C#.

Step 2

In this example we use two textboxes and convert the value based on the first textbox, then show the converted value into the second texbox.

Here is the code of XAML.

<StackPanel Margin="5">
   <TextBlock Style="{StaticResource BasicTextStyle}" Text="Percent grade:" Margin="5" />
   <TextBox x:Name="ValueConverter" Text="70" Margin="5"/>
   <TextBlock Style="{StaticResource BasicTextStyle}" Text="Letter grade:" Margin="5"/>
   <TextBox x:Name="tbValueConverterDataBound"
Margin="5" Width="150"/>
</StackPanel>

Step 3

To create a Custom Converter I will create a converter class that implements the IValueConverter Interface and implements the Convert method in this class. This method takes four types of arguements but we only require the first paremeter that contrains the value to be converted and returned back.

To add a .cs file:

Add-Class-In-Windows-Store-Apps.jpg

Add-NewClass-File-In-Windows-Store-Apps.jpg

Here is the code of the .cs file:
 
public class ValueConverter : IValueConverter
{
        //Convert the textbox value into Grades
    public object Convert(object value, System.Type type, object parameter, string language)
    {
        int _value;
        string _grade = string.Empty;
       //try parsing the value to int
       if (Int32.TryParse(value.ToString(), out _value))
       {
                if (_value < 50)
                    _grade = "F";
                else if (_value < 60)
                    _grade = "D";
                else if (_value < 70)
                    _grade = "C";
                else if (_value < 80)
                    _grade = "B";
                else if (_value < 90)
                    _grade = "A";
                else if (_value < 100)
                    _grade = "A+";
                else if (_value == 100)
                    _grade = "SUPER STAR!";
        }
            return _grade;
     }
    public object ConvertBack(object value, System.Type type, object parameter, string language)
   {
        throw new NotImplementedException(); //doing one-way binding so this is not required.
   }
}

Step 4

Now, in the XAML file I will create a static resource of the converter class and give the key to this resource, so we can use it later for conversion.
<StackPanel.Resources>
    <local:ValueConverter x:Key="GradeConverter"/>                         
</StackPanel.Resources>
Step 5

In this step I will give the static resource that I defined perviously to the result textbox by binding its text property.
<TextBox x:Name="tbValueConverterDataBound" Text="{Binding ElementName=ValueConverter,
       
 Path=Text, Mode=OneWay, Converter={StaticResource GradeConverter}}" Margin="5" Width="150"/>

Here is the full code:
 
<Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
   <StackPanel Margin="5">
    <!-- Add converter as a resource to reference it from a Binding. -->
      <StackPanel.Resources>
         <local:S2Formatter x:Key="GradeConverter"/>                         
      </StackPanel.Resources>
      <TextBlock Style="{StaticResource BasicTextStyle}" Text="Percent grade:" Margin="5" />
      <TextBox x:Name="ValueConverter" Text="70" Margin="5"/>
      <TextBlock Style="{StaticResource BasicTextStyle}" Text="Letter grade:" Margin="5"/>
      <TextBox x:Name="tbValueConverterDataBound" Text="{Binding ElementName=ValueConverter,
             
 Path=Text, Mode=OneWay, Converter={StaticResource GradeConverter}}" Margin="5" Width="150"/>
   </StackPanel>
</Grid>
Step 6

Now, build the application and run it.

You will see that the value of the second textbox is converted from the value in the first textbox; look at:


If you change the value of first textbox, then the converted value will be reflected in the second textbox since I used one way binding.

IValueConverter-Interface-In-Windows-Store-Apps.jpg

Monday, August 19, 2013

Microsoft Visual Studio 2013 and Your App Store




Some Key Features of Visual Studio 2013
Visual Studio Languages
  • .NET FrameWork 4.5.1 : Now, when you compile an app that targets the .NET Framework 4.5.1, you can add binding redirects to the app configuration file if your app or its components reference multiple versions of the same assembly.
  • Visual C++: New features include compiler and STL support for these features:
  1. Default template arguments for function templates
  2. Delegating constructors
  3. Explicit conversion operators
  4. Initializer lists/uniform initialization
  5. Raw string literals
  6. Variadic templates
JavaScript
Block Scoped VariablesYou can use the new let and const keywords to declare variables for which the scope is limited to the block in which they're declared. See let Statement (JavaScript) and const Statement (JavaScript).
Container ObjectYou can create a collection of unique objects by using the Set Object (JavaScript) object, and you can create a collection of key/value pairs by using Map Object (JavaScript) or WeakMap Object (JavaScript).
Your App Store and Visual Studio 2013
Here you can look at the improvements in Windows 8. The main point here is the Start Button in the Taskbar. Another point is the App Store, it has many updated apps. The Windows user experience continues to evolve, and it's getting easier to develop, test, and submit apps to the Windows Store.

The developer samples are here:
Windows 8.1 app samples
Microsoft launched some new APIs and features for developers.
App packagingNew app bundles make app submissions even simpler than before. Resource packs let you offer extras, like localization or assets for high-resolution displays, to users who want them, without affecting disk space, bandwidth, or the app-purchase experience for those who don't.
  • Resource packs
  • App bundles
  • Package identity
  • App bundle deployment
Asynchronous ProgrammingA new scheduler API lets you set the priority of tasks and manage jobs. This helps you write apps that use system resources more efficiently and provide a more responsive experience to users.
Controls (HTML5 and JavaScript)Add new features, like custom commands and enhanced navigation support, by using the new HTML and JavaScript controls. And updates to existing controls make them simpler to use and add features, like drag-and-drop operations. These new and updated controls make it easier than ever to create a full-featured app.
  • AppBarCommand
  • BackButton
  • Hub
  • ItemContainer
  • NavBar
  • WebView
  • Dispose API
  • ListView updates
  • Repeater
  • Template and binding updates
Controls (XAML with C# or C++) Add new features, like date and time pickers and enhanced navigation support, by using the new XAML controls. And updates to existing controls make them simpler to use and more versatile. These new and updated controls make it easier than ever to create a full-featured app.
  • AppBar controls
  • Flyout
  • MenuFlyout
  • FlipView updates
  • CommandBar
  • Hub
  • SettingsFlyout
  • Header support
  • DatePicker
  • Hyperlink
  • TimePicker
  • PlaceholderText
DevicesWith Windows 8.1 Preview, create an app that's ready to connect to a wide range of wired and wireless devices. Your users can then enjoy the mobility and flexibility of Windows 8 devices when they view or create content, at home or on the job.
  • USB
  • Bluetooth
  • Point of Service (POS)
  • Human interface devices (HID)
DirectX programmingWindows 8.1 Preview introduces DirectX 11.2, that brings a host of new features to improve performance in your games and graphics apps.
  • Dynamic shader linking
  • Frame buffer scaling
  • GPU overlay support
  • DirectX tiled resources
  • Direct3D low-latency swap chain present
  • Function linking graph support
  • DXGI Trim API and map default buffer
  • Multithreading with SafeImageSource
  • Composition of XAML visuals
  • Direct2D batching with SafeImageSource
FilesDevelop an app that can easily access user content, and make its own content easier for other apps to discover. You can do this in Windows 8.1 with the enhanced support for in-app file management, a wider selection of user libraries for your app to use, and the ability to push your app's unique content to the Windows Index.
  • File picker updates
  • File comparison
  • New KnownFolders
  • Manage user libraries
  • Retrieve parent files or folders
  • New file "Open with" option
  • Add to the Windows Index
  • Try method for file retrieval
MultimediaNow it's easier to help users both create and play back exciting media experiences. Windows 8.1 Preview offers new ways to capture and process media, a simple way to add playback controls to apps that use XAML, and native support for Encrypted Media Extensions (EME) for HTML5 playback.
  • Video processing
  • MediaElement updates
  • New media-capture features
  • Play To updates
  • HTML5 playback DRM support
NetworkingUse simpler implementation of HTTP for all supported languages, easier communication for your app, and new APIs for location-based mobile scenarios to develop versatile connected apps.
  • New HTTP Client API
  • Background transfer updates
  • HTTP Request filters
  • Real-time connectivity
  • Connected Standby updates
  • Geofence support
  • Wi-Fi Direct
SecurityProvide users a security experience that doesn't feel like a hassle, and keep pace with the latest authentication techniques. We've got new ways to authenticate and manage users, expanded support for signatures and certificates, and new capabilities for stored credentials.
  • Fingerprint authentication
  • Credential Locker updates
  • Windows To Go updates
  • Certificate trust management
  • Web Auth Broker updates
  • App account settings
  • Selective Wipe
  • Smartcards and virtual smartcards
StorePublish, sell, and maintain your app more easily, with commerce support for in-app purchases, new tools for managing your app's offers and tracking its performance, and a number of enhancements to the Windows Store user experience.
  • App onboarding updates
  • In-app commerce support
  • Large in-app purchase catalog support
  • Bing powered Store search
  • New and improved Store pages
  • Automatic app updates
  • Proxy authentication for enterprise scenarios
  • Redeemable credit for Store purchases
ToolsWindows 8.1 Preview also has many updates to the tools and templates that you can use to create Windows Store apps. These improvements can help cut down the work in your development and test cycles.
  • General updates
  • C++ development
  • App Network Analyzer
  • Diagnostics
  • HTML design tools
  • Windows App Certification Kit 3.0
  • JavaScript editor
  • XAML design tools
UX/UINew windowing modes provide users more control over how they use your app. New tile features let you do more with your app's tile. And updates to search, share, and charms create a more consistent general experience for users.

  • New windowing modes
  • Search updates
  • Charms work on every screen
  • Share updates
  • Tile updates
  • Text to speech
  • Work item scheduling with CoreDispatcher

Thursday, August 15, 2013

XAML Editor Improvements in Visual Studio 2013




While many of you like creating XAML using our visual tools, many prefer creating XAML in the code editor as well. Your feedback was heard loud and clear and we have taken a crack at the top XAML editor feature requests in Visual Studio 2013. This blog post describes the new editor features in detail and how you can use them!

IntelliSense for Data Binding

IntellISense for properties of the current data context is now available in binding expressions. In order for the editor to resolve the properties we require the data context to be specified on the view and not set in code-behind. If you choose to specify the DataContext in code-behind you can set the design-time DataContext in the view and we will able to piggyback off that for resolving properties in binding expressions.
Furthermore for getting binding IntelliSense in resources like data templates which may be defined in external resource dictionaries you can either choose to set the design time DataContext on the data template or if you navigate to the data template using Go To Definition (F12) we will do the work required to copy the right DataContext over. It saves you from having to explicitly set the design time DataContext on the data template.

IntelliSense with resolved DataContext

IntelliSense with resolved DataContext

 

IntelliSense with design time DataContext

IntelliSense with design time DataContext
As you can see both ways of setting the DataContext result in the exact same intelliSense.

 

Go To Definition

Go To Definition (F12)  is now enabled on Resources (Local, System & Extension SDK), Bindings, Properties and XAML Elements (UserControls, CustomControls & System types). In the following section, let’s look into the changes in more detail.

 

Resource

Executing Go To Definition on a resource reference will navigate you to the definition of the resource. This works for local, system and resource references from extension SDK’s. When applicable, designer is scoped into the resource on executing Go To Definition. This allows us to copy over the DataContext of the parent control, thus enabling IntelliSense for data bindings inside these resources.
For example, let’s say you call Go to Definition on ApplicationPageBackgroundThemeBrush:

Go to Definition on ApplicationPageBackgroundThemeBrush

Notice that you are taken to the exact location where that resource was defined:

exact location where that resource was defined

 

System type

You can use Go to Definition on System or Extension SDK types. Doing so will navigate you directly to the Object Browser:

Object Browser

 

Local type (Custom control)

UserControl’s and custom controls are generally composed of a type definition and a XAML file defining their look and feel. We wanted to make it super easy to navigate to both the type and the XAML file. Therefore when you call Go To Definition on either of these types we surface both the xaml file and its implementation in the Find Symbol Results window.
For example, let’s say we call Go To Definition on a custom control called CustomControl1:

Go To Definition on a custom control

What gets returned are the results from Generic.xaml as well as CustomControl1.cs:

Return results from XAML as well as CS

 

Binding Expression

You can call Go To Definition on a binding expression. If the DataContext of a binding expression can be resolved, we enable direct navigation to the property definition in code (managed) or to the Object Browser (native). When we are unable to resolve the DataContext of a binding expression, we do a full symbol search (only in managed projects) on the value of the Path property of the binding expression. These results are then surfaced in the Find Symbol Results window.

 

IntelliSense for Resources

While working with resources in the editor you end up switching back and forth between multiple documents to complete a simple resource reference. With IntelliSense for resources you no longer have to do that, resources in your project show up in IntellISense while completing markup extensions. The cases we addressed are:

Setting Grid.Background to a System brush

Setting Grid.Background to a System brush

 

Setting TextBlockStyle to a System style

Setting TextBlockStyle to a System style

 

Setting GridView.Style to a Local resource

Support for "insert snippet" and "surround with" commands in XAML editor

 

Code Snippets

Code Snippets have been a staple feature for all languages in Visual Studio. We have now added support for both “Insert Snippet” and “Surround With” commands in the XAML editor:

clip_image022

Snippets can be imported using the Code Snippets Manager:

Snippets can be imported using the Code Snippets Manager

As of now there are no snippets packaged with the product but we are planning to release some in the very near future. Stay tuned!

Better commenting support

The XML standard does not support nested comments, but we have added support to ensure that the result of commenting a region of code which already contains comments will be standards compliant:

Better commenting support

 

IntelliSense matching

We have updated IntelliSense matching support in the XAML editor to include camel case, substring and fuzzy matching.

Fuzzy matching

Notice how we select StackPanel even though you might have mistyped it as ‘StakPa”.

Fuzzy matching intellisense

 

CamelCase matching

You don’t need to type long Type names anymore. Its abbreviation will work just fine, e.g typing “ABB” will select AppBarButton.

CamelCase matching intellisense

 

Substring matching

For example, typing “Sized” will select VariableSizedWrapGrid.

Substring matching intellisense

 

Start Tag / End Tag refactoring

This feature automatically updates the start or end tag of a XAML element while you are editing its corresponding start or end tag. Moreover adding the ‘/’ character to a start tag will remove the corresponding end tag without affecting the element’s inner content.

Tag refactoring

Tag Refactoring

 


Removing the end tag

Removing the end tag

 

Other Improvements

We have made some significantimprovements to the performance of the editor. Instant outlining and faster IntelliSense startup are some of the areas we focused on during this release . For example, we brought down the IntelliSense startup time of one of our large WPF test projects from over 24 seconds to 6.78.
Some of the features described here will not work in Source Code mode as we require the XAML view to be built in order to resolve resources and binding references. All the improvements highlighted here will be available for all XAML platforms (WPF, Silverlight, Windows Phone and Windows Store) in the next public release of Visual Studio.
The markup editor also provides support for other new Visual Studio editor features like:
  • Move line up/down (Alt + Up Arrow, Alt + Down Arrow)
  • Scrollbar enhancements