Jump to: navigation, search

Difference between revisions of "XAML Basics"


(Binding options)
Line 110: Line 110:
 
</Interactivity:Interaction.Behaviors>  
 
</Interactivity:Interaction.Behaviors>  
 
</source>
 
</source>
 +
  
 
== Templates ==
 
== Templates ==

Revision as of 09:21, 28 April 2020

Basic guide describing the first steps in how to use and build your XAML code.

Introduction

This language bases upon XML and is a programming language like every other but used for a distinctive purpose, namely for describing User Interfaces. These can be built for Windows or mobile applications that use Windows Presentation Foundation (WPF), UWP, and Xamarin Forms, so basically many different forms of applications. We are using XAML in combination with C# in the MVVM Pattern, which will be explained in a different section.

Getting started

You start building your UI with different Controls. Starting with a blank Page, Window etc. you can add the elements that you need. Two buttons here, a few textboxes there and after some time you will have your finished UI. Obviously, it’s not that easy, but that is how you basically work. The syntax is quite easy, just like HTML, every element starts with pointy brackets <element> and ends almost the same but with an additional slash </element>. The structure is a little bit like a tree structure but also consists out of elements that are nested in other elements. Every element has its own attributes that have the ability to describe its owner with its values. For example, we have a button and some of the attributes are the Width, Height and Color. By setting values in these attributes you can change the visual appearance of your button and adapt it to your needs.

Environment Setup

Sometimes it’s very hard to start properly with a programming language, because of the variety of topics in how and where to start. In order to build a basic understanding, we want to show you some of the tools we are using to customize XAML and also explain why.

Visual Studio

Visual Studio is one of the most common tools for software developers, because it has handy features that you need when creating a project. In this tool you’ll have a debugger, a compiler, a tree-viewer of the structure of your XAML (e.g. Page - Grid - Button – TextBlock), and it also shows your syntax errors, which is not entirely included in the further tools that will be further explained. But because it has so many features, beginners often have a hard time to handle this mighty tool. Visual Studio has also a nice feature, which allows you test different scales for various devices. This comes in practical when designing for e.g. desktop and tablet. For automatic formatting and saving some time we use the ‘XAML Styler’ extension with the default settings in Visual Studio.
-> Creating a test project Having a test project with all the needed styles and controls etc. is very helpful to see your XAML code in a ‘neutral’ environment. Of course, there will be some dependencies when implementing your code into the project environment, but still this is a good way especially for beginners to see how the default objects behave and how you can configure them.

Visual Studio Code

This tool doesn’t have as many features (e.g. compiling and debugging) as Visual Studio. Also that’s why I think this would be the best alternative, it is just way less overwhelming. When using Visual Studio Code you can use the XML Tools Extension which formats the text with shifting, also there is IntelliSense support until some degree.

Notepad ++

It’s a simple editor with the simple, but very nice feature that shows where a container opens and closes. E.g. when you have five or more grids in your code, you will quickly loose overview. VSC unfortunately doesn’t show that and you have to add extra comments in order to explain where a container begins and ends.


MVVM pattern

It is important to know how we build our applications in order to understand how XAML is being used. There are many different patterns a company can use, but we decided this pattern would be the most efficient to work with.

MVVM Pattern

A. Model -
The model is used for holding the data. The model represents the actual data and/or information we are dealing with. An example of a model might be a contact (containing name, phone number, address, etc).

B.View -
The User Interface, what the user sees, is described in here. The view is what most of us are familiar with and the only thing the end user really interacts with. It is the visual presentation of the data, which is described with XAML code.

C. ViewModel -
The ViewModel might take input from the view and place it on the model, or it might interact with a service to retrieve the model, then translate properties and place it on the view. It also exposes methods, commands, and other points that help maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events in the view itself. The ViewModel acts basically as an interface between Model and View that provides data binding between View and Model data.


Bindings

Data Binding is the process of connecting a display element, such as a user interface control, with the information that populates it. This connection provides a path for the information to travel between the source and the destination. For example, consider a simple application. You have things like a Search box, Buttons, TextBlocks etc. Each of these is a user interface control that accepts or displays, information for you. We bind to two different things, that is either a property, which lays beneath on a ViewModel as we saw in the MVVM pattern section. But we also bind to a MetaProperty, which is a property in an UBIK database.

Binding modes

Modes

  • OneWay — values are transferred from the source to the target
  • OneWayToSource — values are transferred from the target to the source
  • TwoWay — values are transferred both ways between source and target
  • OneTime — data goes from source to target, but only when the BindingContext changes

Binding options

  • Standard (Recommended) -> Attribute = ”{Binding Name of Property}”
Text = “{Binding CommentText}”

  • On a MetaProperty -> Attribute =”{Binding Values [Name of MetaProperty]}”
Text=”{Binding Values[MP_SCOPECHANGE]}”

No Modes available
This is a special Binding option, and as above mentioned, you can’t use any of the Modes with it. With this Binding you are restricted to just being able to read this property. When changing a value in the client it won’t arrive to the database.

  • On a MetaProperty with an additional UBIK Property -> Attribute = ” {Binding PropertyItems [Name of MetaProperty].DisplayValue}”
Text=”{Binding PropertyItems[MP_SCOPECHANGE].DisplayValue}”

No Modes available for several UBIK properties
But there are exceptions where you CAN actually use Modes. The property ‘Display’ provides this option.

Text=”{Binding PropertyItems[MP_SCOPECHANGE].Value, Mode=”TwoWay”}”

This is NOT recommended, but still documented in case you’ll need it and nothing else works or you see it somewhere and you have no clue what it does. This Binding has the additional aspect that, with the second kind of the UBIK property, values can be saved back to the database but ONLY when you add a command to the object where your Binding is placed. When talking about a UBIK property, we mean properties from an UBIK ViewModel, which is the same as a simple property on a ViewModel in the end. The only difference is that they have certain limitations, as for example not all of the modes are available for all UBIK properties.

  • On an element in your XAML code -> Attribute = “{Binding attribute, ElementName= x:Name}”
Background=”{Binding Background, ElementName=ValueBall}”

This Binding can be very practical, if you want ‘copy’ their value of an attribute or switch e.g. the Visibility of an element by making it dependent of the attribute value on a different element. There are various possibilities in how to bind to an ElementName. Also, the usage of a converter and a parameter is possible, which often comes handy.

  • Using a converter and an additonal parameter could look like this -> Attribute = “{Binding ElementName=element, Path=attribute, Converter={StaticResource converter}}”
<!--With a converter-->
<Grid Visibility="{Binding ElementName=ScopeChangesRadioButton, Path=IsChecked, Converter={StaticResource BoolToVisConverter}}"/>
<!--With an additonal parameter-->
<Grid Visibility="{Binding Values[MP_SCOPECHANGE], Converter={StaticResource EqualToColConverter}, ConverterParameter=30}"/>


  • Binding a command to an Interactivity -> Command ="{Binding CustomCommand}"

Bindings are also used to bind custom commands to a command element. In this example we have even two commands bound to:

<Interactivity:Interaction.Behaviors>
        <Core:EventTriggerBehavior EventName="Tapped">
                <Core:InvokeCommandAction Command="{Binding NavigateToChildrenCommand}"/>
        </Core:EventTriggerBehavior>
        <Core:EventTriggerBehavior EventName="RightTapped">
                <Core:InvokeCommandAction Command="{Binding BranchDownloadCommand}"/>
        </Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>


Templates

The function of the templates is basically re-describing an element (for example button or a textbox) you want to use, but a template can also define whole areas. You will see that we work very often with templates when customizing in the UBIK environment.
The default templates can be found, in general, on the internet. Or, if you are using Visual Studio, you can right-click on the control in the Visual Studio Designer and choose the option ‘Edit Template > Edit Copy’.

A Control Template describes the visual appearance and structure of a control. All of the UI elements have some kind of appearance as well as behavior, e.g., Button has an appearance and behavior. Click event or mouse hover events are the behaviors which are fired in response to a click and hover, and there is also a default appearance of button which can be changed by the Control template.

A Style Template describes a uniform look to a set of controls. Styles give us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look.

A Data Template defines and specifies the appearance and structure of the collection of data. It provides the flexibility to format and define the presentation of the data on any UI element. It is mostly used on data related Item controls such as ComboBox, ListBox, etc.

Style/Control/Data Definition in UBIK
In the UBIK surrounding we have a UBIKThemes.xaml file for our Client which describes a lot of style/control templates and colors etc. These are also configurable for our customizers, so they can adapt it to each project. But this process got more and more complicated, you just couldn’t have an overview of the things that you changed and the things that are here by default. In order to avoid such cases we created a new way to adapt this particular file. The process would look like this, you copy the style/color/control and create a new UBIKThemes file where you place the things you want to customize. The client will go over the default UBIKThemes and after that over your customized one, the default templates will be replaced -> identified via x:Key, so be careful to have them identical.

Namespaces

Namespaces are very important in your XAML code, they identify the libraries of what controls/elements you can use. You can see them referenced on the top of your file directly in the parent object like DataTemplate, Window, Page etc. A few are already defined in your .xaml file per default. When you forget a required namespace or the spelling is not correct, you can crush your whole app and it’s hard , especially without debugging, to recognize that issue. It is good to check for misspelled or missing namespaces first when something doesn’t work. An example for a namespace is: xmlns:converters="using:UBIK.WinX.Converters" which you need when using converters in your XAML code that lays directly in the solution file.

What can I customize in UBIK?

In the previous articles about XAML customizing it was all about how to create code from the beginning and what you need for it. In the UBIK environment it’s a little different, because we have already predefined XAML files (Data/Control Templates) for our standard UI. Of course, you have the option to override the existing ones or add new templates according to your needs. Customizing in our UBIK Environment occurs a lot through templates which can define different areas in the app. Only templates are customizable in UBIK, there are some areas which are not yet to be customizable. You can access the XAML templates via the Developer Mode in the Client. By activating it you can extract the needed XAML file into your XAML folder, further information can be found in the wiki article of the Developer Mode.