DeutschEnglish

Jan 30

Making WPF button’s Pressed state work with touch input

The short story:

In order for a WPF Button control to trigger the Pressed VisualState when using finger interaction on a touch screen (similarly to clicking with a mouse), it seems to be necessary to completely deactivate the press-and-hold right mouse button emulation by setting the Stylus.IsPressAndHoldEnabled attached property to false.

The long story:

After all those articles covering Windows Phone and WinRT Apps, it’s time for something different. We’re currently working on a WPF project that is intended to run in fullscreen mode and be operated using finger touch events on a touch screen. Since the application does not feature any complex touch gestures but is only controlled through buttons that can be pressed, we decided to refrain from referencing a dedicated touch handling framework and instead let each button press be handled as if it was a simple mouse click.

To signal a user that a button is pressed when touching it with the finger, we implemented visual states on all buttons in the application: On the Pressed VisualState, a button changes its color to appear as a physical button that is currently pressed:

<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
	<Setter Property="Template">
		<Setter.Value>
			<ControlTemplate TargetType="Button">
				<Grid>
					<Border x:Name="ButtonBorder" Background="LightGray" BorderBrush="DarkBlue" BorderThickness="3" CornerRadius="5">
						<ContentPresenter Margin="20" />
					</Border>

					<VisualStateManager.VisualStateGroups>
						<VisualStateGroup x:Name="CommonStates">
							<VisualState x:Name="Normal"/>
							<VisualState x:Name="MouseOver"/>
							<VisualState x:Name="Disabled"/>
							<VisualState x:Name="Pressed">
								<Storyboard>
									<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonBorder" Storyboard.TargetProperty="Background">
										<DiscreteObjectKeyFrame KeyTime="0">
											<DiscreteObjectKeyFrame.Value>
												<SolidColorBrush Color="DarkGray" />
											</DiscreteObjectKeyFrame.Value>
										</DiscreteObjectKeyFrame>
									</ObjectAnimationUsingKeyFrames>
								</Storyboard>
							</VisualState>
						</VisualStateGroup>
					</VisualStateManager.VisualStateGroups>
				</Grid>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
</Style>

The application was developed and basically tested using common monitor and a mouse. When we connected the machine to a touch screen monitor to thoroughly test the first few screens, it turned out that the color change on currently pressed buttons – that had previously worked using mouse clicks – was gone, the button could actually be operated using finger touch events (and the command connected with it was executed), but the animation defined for the Pressed state was not considered.

The solution:

There are two things to distinguish here:

  • The button’s Click event is handled irrespective of input device, both mouse click and finger touch are forwarded to the same event handler and treated in the same way. This explains why the business logic connected with the button’s command is successfully executed independently from the visual state change.
  • The VisualState changes are triggered by dedicated mouse events: For example, the Pressed state is reached when the button’s OnMouseLeftButtonDown event occurs. The finger touch-and-hold event is usually mapped to a click with the right mouse button (when tapping on the screen and not instantly releasing the finger, Windows interprets this as right-click operation) – the OnMouseLeftButtonDown event never fires, and the Pressed state is never reached!

Fortunately, this can be fixed easily by completely disabling the right-click simulation, either for a distinct button or for the whole window / page, by setting the Stylus.IsPressAndHoldEnabled attached property to false:

<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
	<Setter Property="Stylus.IsPressAndHoldEnabled" Value="False"/>
	...
</Style>

Permanent link to this article: http://www.mobilemotion.eu/?p=1396&lang=en

Jan 22

Toggle comments bug in Xamarin Studio

I’m currently working on several Xamarin project, among others adapting the MVVMbasics framework to support the Xamarin.Forms target platform. This means I’m playing around a lot with Xamarin Studio, and today I located a minor but annoying bug in version 5.7 of the Xamarin Studio development environment:

Xamarin Studio features the useful Toggle Line Comment(s) command that can be found either in the text editor’s context menu or in the Edit > Format > menu, or invoked using the Ctrl+Alt+C hotkey. In the C# editor, this command adds a code comment (//) at the beginning of the line the cursor is positioned in, or removes an existing comment. If several full lines are selected, it adds the comment markers to the beginning to all currently selected lines.

In the XML editor, however, when several full lines are selected, the command creates an XML comment (<!– –>) that starts at the beginning of the first selected line, and reaches not only until the end of the last selected line but until the end of the line that follows the last selected one. The following two images illustrate this behavior by showing a sample XML code snippet before and after applying the Toggle Line Comment(s) command:

Short line

Short line
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

I’ve just reported this behavior to the official Xamarin bug tracking system, let’s see what they do with it. Meanwhile, it’s good to know that in the XML editor, you should always select one line less than you’d actually like to comment!

Permanent link to this article: http://www.mobilemotion.eu/?p=1400&lang=en

Jan 20

An elegant INotifyPropertyChanged implementation #4

This is the last part of a series of articles discussing an optimal implementation of the INotifyPropertyChanged event. As we’ve managed to implement a maintainable bindable property declaration by removing all string references, there are still two open questions left: How can we reduce the amount of code needed for one property declaration, thus reducing the effort in actually writing the code and at the same time making the resulting code more readable?

In a first step, let’s try to reduce the actual property declaration code to as few lines as possible! Unfortunately, we won’t ever be able to use auto-properties since we need to intercept the property’s setter method, so there’s no way to get rid of the backing field or the manual implementation of getter and setter method – however, we can shorten those! The property’s getter is already as short as possible, containing just one line that returns the backing field’s content. In contrast, the setter method is quite verbose and can surely be simplified!

Remember that, as I shortly mentioned in the first part of this article series, a typical bindable property’s setter method needs to do the following things:

  1. Compare old and new value, (to ensure PropertyChanged is only raised on actual changes),
  2. if the two are different, set the backing field’s value,
  3. raise the property’s PropertyChanged event,
  4. optionally raise other properties’ PropertyChanged events (in case some other properties depend on the current one),
  5. and optionally raise some Commands’ CanExecuteChanged events (in case some Commands’ execute conditions depend on the current property)

The first three steps are necessary for all bindable properties, the fourth one is optional. The fifth step (informing some Command that its execute condition has changed) can actually be omitted and moved to the actual Command’s implementation (I’m planning a separate article explaining this smart ICommand implementation in detail), so I’ll ignore this step for the time being.

To make the property setter shorter and more readable, we simply move all the contained code to a generic helper method that can be called from within every property declaration! I call this helper method Set(), since that describes quite well what it’s doing (and is a name as short as possible), and its signature looks like this:

protected void Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null)

As you can see, we pass the backing field (by reference, since we’ll need to update it’s content!), the new value, and the property name (for raising the PropertyChanged event). The latter can be omitted to be automatically replaced by the calling property’s name, as we’ve learned in part #2 of this series.

Now we’re ready to fill in the Set method’s body to make it process all the steps listed above. First, to compare old and new value, we can not rely on type-specific comparison method (such as String.Equals(...)) any more, since the Set method shall work for all types. Instead, I suggest using the Object.ReferenceEquals method that checks whether two object instance are the same instance:

if (!ReferenceEquals(field, value))
{
	....
}

Replacing the backing field’s old value with the new one is a simple assignment, and raising the PropertyChanged event is not difficult either since we can rely on the RaisePropertyChanged method defined earlier (we just need make sure that we pass the property name explicitly this time, otherwise the PropertyChanged will be raised with a parameter that says Set instead of the actual property name!):

protected void Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
	if (!ReferenceEquals(field, value))
	{
		field = value;
		RaisePropertyChanged(propertyName);
	}
}

This implementation covers the first three (mandatory) steps listed above. In order to also take care of the fourth one (the optional), we could create an overload of the Set method that accepts an additional dependent property whose PropertyChanged event shall also be raised:

protected void Set<T>(ref T field, T value, Expression<Func<T>> dependentProperty,
                      [CallerMemberName] string propertyName = null)
{
	if (!ReferenceEquals(field, value))
	{
		field = value;
		RaisePropertyChanged(propertyName);
		RaisePropertyChanged(dependentProperty);
	}
}

(Of course, in some cases it might be necessary to raise the PropertyChanged event for multiple dependent properties, in this case we’d need another overload that accepts a collection of additional properties, but for the sake of simplicity I omit this step for now.)

One final step can be done to reduce the amount of code and at the same time make the code more maintainable: We should relocate both the RaisePropertyChanged methods and the Set methods to a separate class – let’s name it BaseViewmodel that every production Viewmodel can inherit from:

public void BaseViewmodel : INotifyPropertyChanged
{
		public event PropertyChangedEventHandler PropertyChanged;

		protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
		{
			PropertyChangedEventHandler handler = PropertyChanged;
			if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
		}

		protected virtual void RaisePropertyChanged<T>(Expression<Func<T>> property)
		{
			string propertyName = ((MemberExpression)property.Body).Member.Name;
			RaisePropertyChanged(propertyName);
		}

		protected void Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
		{
			if (!ReferenceEquals(field, value))
			{
				field = value;
				RaisePropertyChanged(propertyName);
			}
		}

		protected void Set<T>(ref T field, T value, Expression<Func<T>> dependentProperty,
		                      [CallerMemberName] string propertyName = null)
		{
			if (!ReferenceEquals(field, value))
			{
				field = value;
				RaisePropertyChanged(propertyName);
				RaisePropertyChanged(dependentProperty);
			}
		}
}

This way, we’ll never ever need to write those methods again, just reference the BaseViewmodel class! So our sample PersonViewmodel class looks as clean as:

class PersonViewmodel : BaseViewmodel
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set { Set(ref _firstName, value, () => FullName); }
    }
 
    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set { Set(ref _lastName, value, () => FullName); }
    }
 
    public string FullName
    {
        get { return String.Format("{0} {1}", FirstName, LastName); }
    }
}

Unfortunately, this is as far as we get. The only way to make these bindable property declarations even shorter would be the use of auto-properties (e.g., public string FirstName { get; set; }) – however, you won’t be able to pack the PropertyChanged event raising mechanism into these. With current technology (.NET 4.5, C# 6) it’s not possible to adapt a property’s setter method (and, for example, inject the RaisePropertyChanged call into it), not even using Reflection.

That said, there are in fact ways to make auto-properties bindable (there exist libraries out there that allow using Attribute-marked auto-properties), but these build on IL code instead of the C# language. Since this is kind of a different story, I’ll discuss this approach in a separate series of articles

Permanent link to this article: http://www.mobilemotion.eu/?p=1376&lang=en

Jan 13

An elegant INotifyPropertyChanged implementation #3

The previous article showed how to implicitly inform the PropertyChanged event about the changed property’s name without explicitly passing it as string value. However, there are still open questions: For example, how to raise the PropertyChanged event to indicate that another property (that depends on the current one) has changed? Or, what to do if you’re stuck with a .NET version older than 4.5 in which the CallerMemberName attribute is not available?

In this case, we still need to pass the changed property’s name to the RaisePropertyChanged method, but we’d like to not pass it in form of a string parameter in order to simplify code refactoring. The idea is to pass the changed property as lambda expression, and within the RaisePropertyChanged method parse this expression to retrieve the property’s name (its name as string type is still necessary since it needs to be included in the PropertyChangedEventArgs).

To do so, we create an overload to the existing RaisePropertyChanged method that expects a lambda expression as parameter, resolves this expression, retrieves the property’s name that is represented by the expression, and finally invokes the original RaisePropertyChanged method with this name as parameter:

protected virtual void RaisePropertyChanged<T>(Expression<Func<T>> property)
{
    string propertyName = ((MemberExpression)property.Body).Member.Name;
    RaisePropertyChanged(propertyName);
}

What’s happening whithin this method implementation, especially in the first line that includes all the reflection magic? Let’s walk through it step by step:

  1. We’re retrieving the lambda expression’s content by calling its Body property.
  2. Since we’re expecting the whole expression to represent a property, we cast its content to type MemberExpression.
  3. To actually access the passed property, we call the resulting MemberExpression’s Member property.
  4. Finally, what we’re really interested in is this property’s name – this is stored as string type in the member’s Name property!
  5. Now, to avoid redundant code, we don’t raise the PropertyChanged event directly, and instead call the existing overload of the RaisePropertyChanged and let it do the rest.

With this method overload available within our sample PersonViewmodel, we can get rid of both string typed property references within the FirstName property’s setter:

private string _firstName;
public string FirstName
{
	get { return _firstName; }
	set
	{
		if (!_firstName.Equals(value))
		{
			_firstName = value;
			RaisePropertyChanged();               // Property name automatically filled in by the [CallerMemberName] attribute
			RaisePropertyChanged(() => FullName);  // Property referenced as lambda expression
		}
	}
}

Obviously, this approach could be used for both use-cases: To indicate that another property has changed as well as that the calling property itself has changed, since we could write the first invocation of the RaisePropertyChanged also as RaisePropertyChanged(() => FirstName); – this will still fulfill our aim of writing refactoring-friendly code since it omits string variables. You’ll even be forced to do so if you’re targeting a .NET version older that 4.5 that doesn’t support the CallerMemberName attribute. However, I strongly recommend to use the [CallerMemberName] approach whenever possible, because

  • it does not rely on reflection and is therefore much faster at runtime,
  • and (obviously) even if it seems fine to pass the changed property as lambda expression instead of string value, its even more comfortable to pass no parameter at all!

Now that we’ve managed to completely get rid of all string based property references, there are still two more open questions: The next part #4 will show how to implement the INotifyPropertyChanged interface ss short and readable as possible!

Permanent link to this article: http://www.mobilemotion.eu/?p=1370&lang=en

Jan 06

An elegant INotifyPropertyChanged implementation #2

Let’s start with the third one of the aims specified in the first part of this series of articles: Get rid of the string type parameter that passes the updated property’s name to the RaisePropertyChanged method!

.NET 4.5 introduced a new feature commonly referred to as Caller Information. This includes three attributes that may be assigned to optional parameters of any .NET method, and that represent different characteristics of the code that actually calls this specific method – the optional parameters marked with one of these attributes are replaced by the actual values at compile time. The following three attributes are available:

  • CallerFilePathAttribute (Full path of the source file that contains the caller, as string)
  • CallerLineNumberAttribute (Line number in the source file at which the method is called, as int)
  • CallerMemberNameAttribute (Method or property name of the caller, as string)

The third attribute CallerMemberName is interesting in the context of INotifyPropertyChanged: It can be used to pass the updated property’s name to the PropertyChanged event’s rasing method automatically.

Let’s take a look at the implementational details! As explained in detail in the blog post The very basics of MVVM, every class that implements the INotifyPropertyChanged interface (such as each (View-)Model class) needs to include a public event PropertyChanged, typically complemented by a convenience method to actually raise this event:

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void RaisePropertyChanged(string propertyName)
{
	PropertyChangedEventHandler handler = PropertyChanged;
	if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

Since the CallerMemberName attribute may only be applied to optional parameters, the first step would be to turn the RaisePropertyChanged method’s propertyName parameter into an optional one:

protected virtual void RaisePropertyChanged(string propertyName = null)
{ ... }

This is perfectly valid, since – according to MSDN – a PropertyChanged event containing null as property name indicates that all properties within the Model class have changed, and the whole View must be updated.

Now, actually inserting the CallerMemberName attribute is simple – the method’s content doesn’t need to be changed:

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
	PropertyChangedEventHandler handler = PropertyChanged;
	if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}

This allows us to call the RaisePropertyChanged method without passing the calling property’s name, as from within our sample PersonViewmodel:

private string _firstName;
public string FirstName
{
	get { return _firstName; }
	set
	{
		if (!_firstName.Equals(value))
		{
			_firstName = value;
			RaisePropertyChanged();
			RaisePropertyChanged("FullName");
		}
	}
}

What happens between the lines is the following: The sample property contains two references to the RaisePropertyChanged method, the first one is missing its parameter while the second one specifies the string parameter as usual. During compile time while converting C# code to Intermediate Language (IL) code, the compiler stumbles across the first method invocation, recognizes that a parameter marked with the CallerMemberName attribute has been omitted, and inserts the calling property’s name there as string – just as if we would have written RaisePropertyChanged("FirstName");. In contrast, the second method invocation is not manipulated by the compiler since a string parameter has manually been specified, thus overriding the CallerMemberName attribute.

What’s really important in this context is to notice that there’s no reflection involved – the CallerMemberName attribute is simply replaced by the calling method’s or property’s name as string at compile time, so there’s no need to go searching for the calling object using reflection mechanisms at runtime. This implies that the [CallerMemberName] approach has no impacts on runtime performance – in fact, it’s exactly as fast as the traditional approach of manually passing the property name, since both approaches produce the same IL code!

This approach makes it needless to pass property names as string variables in the most common use-cases of the RaisePropertyChanged method: To let a property indicate that itself has changed. However, as we’ve seen in the code samples above, there are still cases where it’s necessary to manually pass string values: To indicate that another property has changed! We’ll cover this in the next part #3.

Permanent link to this article: http://www.mobilemotion.eu/?p=1361&lang=en

Dec 31

An elegant INotifyPropertyChanged implementation #1

As explained in the article series The very basics of MVVM, each (View-)Model property to be available for Data Binding in the View layer needs to raise the PropertyChanged event whenever its content changes. This is necessary to inform View classes (pages, windows, etc.) that are registered to this event about changes in the data, in order to make the View update and redraw itself.

Speaking about code, this event is typically raised directly within the property’s setter. Unfortunately, this fact makes it impossible to implement data binding properties as simple auto-properties, instead it’s necessary to create a private backing field and implement the public property’s getter and setter from scratch – and, moreover, it results in quite long setter methods: Such a property’s setter needs to execute at least three steps:

  1. Compare old and new value, (to ensure PropertyChanged is only raised on actual changes),
  2. if the two are different, set the backing field’s value,
  3. and finally raise the PropertyChanged event

A typical Viewmodel contains several data binding properties, implementing each of them as described above is repetitive and error-prone. Fortunately, there exists a variety of libraries that can help shorten those property declaration, e.g. most MVVM frameworks provide helper functions aiming at this, but I think it’s always good to know how to do things from scratch – in practice, you’ll of course let one of the established frameworks do the work for you, but wouldn’t it feel good to actually know how the black magic within these frameworks is implemented?

The aim of this blog post (and the next ones) is to show different ways of implementing the INotifyPropertyChanged in a more elegant and efficient way, explain why there are different ways at all, and discuss which approach to use for what use-case. In summary, we’re looking for an INotifyPropertyChanged implementation that

  • makes coding faster, by reducing the necessary amount of code to write,
  • makes code more readable, by reducing each property declaration to as few lines as possible, and
  • makes code more maintainable (Have you ever been annoyed by the PropertyChanged event expecting the changed property’s name as string? How on earth should someone be able to refactor code that contains property names in string variables?)

Before actually starting with the implementational issues, I’d like to point out that there are actual two different reasons for raising the PropertyChanged event from within a property’s setter. Consider the following example of a simple Viewmodel that contains three bindable properties (I’ve omitted the actual PropertyChanged event and the RaisePropertyChanged method’s implementation to shorten the code snippet):

class PersonViewmodel : INotifyPropertyChanged
{
	private string _firstName;
	public string FirstName
	{
		get { return _firstName; }
		set
		{
			if (!_firstName.Equals(value))
			{
				_firstName = value;
				RaisePropertyChanged("FirstName");
				RaisePropertyChanged("FullName");
			}
		}
	}

	private string _lastName;
	public string LastName
	{
		get { return _lastName; }
		set
		{
			if (!_lastName.Equals(value))
			{
				_lastName = value;
				RaisePropertyChanged("LastName");
				RaisePropertyChanged("FullName");
			}
		}
	}

	public string FullName
	{
		get { return String.Format("{0} {1}", FirstName, LastName); }
	}
}

The FullName property does not contain a backing field and a setter at all, since it relys on the other two properties and is just a combination of those two. Therefore it does not raise the PropertyChanged event on it’s own. Instead, both the FirstName and LastName properties call the RaisePropertyChanged() method twice within their setters:

  • Once passing their own property names as parameter, to indicate that their own content has changed,
  • and once again passing the FullName property’s name, to indicate that its content has also changed and potential View controls displaying the FullName property’s content need to be redrawn also!

We’ll see that there exist different approaches to simplify raising the PropertyChanged event for those two cases in the following articles. Let’s just step into the first one: An elegant INotifyPropertyChanged implementation #2!

Permanent link to this article: http://www.mobilemotion.eu/?p=1359&lang=en

Dec 22

[MVVMbasics] Dependency Injection into Viewmodels and Services

Notice

All blog posts with a title that starts with [MVVMbasics] are related to the MVVMbasics framework. If you are only interested in my regular blog posts and not in MVVMbasics, ignore these. To list all articles covering MVVMbasics, go to http://mvvmbasics.mobilemotion.eu/documentation!

One of the core features of the MVVMbasics framework is the global ServiceLocator. This object holds references to all services preent within the project, but instantiates them not until they are used for the first time. In older versions of the framework (until 2.0), the global ServiceLocator instance would automatically be injected into each Viewmodel that inherits from BaseViewmodel and could be accessed through the Viewmodel’s ServiceLocator property. From version 2.1 on, the ServiceLocator property in each Viewmodel is considered deprecated (which means it still works and it’s therefore not necessary to refactor existing projects instantly, but it might be removed from the framework in future versions).

The new way of injecting the global ServiceLocator instance into Viewmodels and accessing Services from within Viewmodels is to provide a Viewmodel constructor that accepts one parameter of type ServiceLocator. Every Viewmodel that derives from BaseViewmodel will be instantiated using this constructor, if available. The global ServiceLocator instance can be stored in a private field within this construtor, which allows access to Services from everywhere within the Viewmodel:

public class MyViewmodel : BaseViewmodel
{
	private readonly ServiceLocator _serviceLocator;
	
	public MyViewmodel(ServiceLocator serviceLocator)
	{
		_serviceLocator = serviceLocator;
	}
	
	private void SomeMethod()
	{
		_serviceLocator.Retrieve<ISomeService>().SomeServiceMethod();
	}
}

Compared to the old approach of auto-injection, this architecture brings about two advantages: The OnServiceLocatorAvailable method is not necessary anymore, and the ServiceLocator instance can also be injected into other Services, discussed in the following two sections:

Accessing Services from within a Viewmodel’s constructor:

In older versions of the MVVMbasics framework, the automatic injection of the global ServiceLocator instance happened shortly after the Viewmodel’s constructor method. This means that it was impossible to access Service methods from within a Viewmodel’s constructor – trying to do so would result in a NullReferenceException since ServiceLocator was still null within the constructor. Therefore the OnServiceLocatorAvailable method was introduced that could be overwritten to be informed as soon as the ServiceLocator instance was actually available. Since in version 2.1, the ServiceLocator instance is passed directly to the constructor as parameter, this method is not necessary any more and will also be marked deprecated.

Using the ServiceLocator within Service instaces:

In some cases it might be useful to access Service methods not only from within Viewmodels but also in other Services. Therefore it’s now possible to inject the global ServiceLocator instance into Service classes the same way as into Viewmodels:

[MvvmService]
public class MyService : IMyService
{
	private readonly ServiceLocator _serviceLocator;
	
	public MyService(ServiceLocator serviceLocator)
	{
		_serviceLocator = serviceLocator;
	}
	
	private void SomeServiceMethod()
	{
		_serviceLocator.Retrieve<ISomeOtherService>().SomeOtherServiceMethod();
	}
}

Permanent link to this article: http://www.mobilemotion.eu/?p=1351&lang=en

Dec 18

[MVVMbasics] MVVMbasics and the UI thread

Notice

All blog posts with a title that starts with [MVVMbasics] are related to the MVVMbasics framework. If you are only interested in my regular blog posts and not in MVVMbasics, ignore these. To list all articles covering MVVMbasics, go to http://mvvmbasics.mobilemotion.eu/documentation!

In .NET front end applications, all code that accesses user interface elements needs to be executed on the main UI thread. Business logic, however, might run on separate threads – for example, network or NFC communication callbacks are usually executed on separate threads, as well as long-running business logic that is typically assigned to a separate thread intentionally in order to not block the graphical user interface.

If such code blocks shall be able to update the user interface, the statements that actually access UI elements in order to update them need to be explicitly assigned back to the UI thread. All common platforms (such as Windows Store, Windows Phone, WPF, etc.) feature some dispatcher object that takes care of scheduling certain statements to be executed on the UI thread: As developer, you don’t need to find the actual UI thread and assign code statements to this thread, instead you simply instruct the dispatcher to do that for you.

Unfortunately the dispatcher pattern is realized in different ways on those platforms – they all have their own implementation of dispatcher objects that reside within different namespaces and offer varying methods. When developing applications that target multiple platforms, there is no common way of accessing a single dispatcher object from within cross-platforms Viewmodels – however, business logic is typically executed on the MVVM Viewmodel layer, so platform-dependent implementations are not a useful alternative either since this implies that business logic is implemented redundantly for each target platform.

This is where the smart dispatcher that is integrated in MVVMbasics version 2.1 (and higher) comes into play: If you’re fully implementing the MVVMbasics pattern and derive views from the BaseView class and the application class from BaseApplication, all Viewmodels derived from MVVMbasics‘s BaseViewmodel class provide the new RunOnMainThread(Action a) method. This method checks whether a certain action would (if simply executed) run on some separate thread that does not have access to the UI thread, and if so instructs the dispatcher to assign it to the UI thread.

Using the MVVM pattern, direct access to UI elements is typically replaced by data binding. This means, only the PropertyChanged event that informs the UI about changes in the underlying data needs to be raised on the UI thread. When using the MVVMbasics Set method to update a data binding property from within a Viewmodel, from version 2.1 on the PropertyChanged event raising mechanism is automatically invoked using the dispatcher if currently not running on the UI thread, which means that it is not necessary to wrap property assignments in the above-mentioned RunOnMainThread method – this is done automatically by the MVVMbasics framework!

Permanent link to this article: http://www.mobilemotion.eu/?p=1342&lang=en

Dec 16

New version MVVMbasics 2.1 available

MVVMbasics 2.1 features a common way for dependency injection of the global service locator into both Viewmodels and Services, as well as a smart UI dispatcher. Also available is a new version of the Visual Studio project templates which now handle the Windows Phone 8.1 back button correctly.                          

Permanent link to this article: http://mvvmbasics.mobilemotion.eu

Dec 10

Crashing the visual XAML editor

I’m back from vacation and just stumbled across a small problem in the WinRT framework. In an earlier blog post, I described how to be notified when a Windows Store App is "minimized" (for example because the user presses the Windows button, or because another app becomes active) by subscribing to the current window’s VisibilityChanged event. When implementing this solution, you’ll probably end up with a line similar to the following in a page’s constructor:

Window.Current.VisibilityChanged += OnVisibilityChanged;

…and the OnVisibilityChanged event handler’s implementation somewhere else. The problem is, when opening this page in Visual Studio’s embedded XAML editor (you know, the one that tries to visualize the page’s content), in some cases you’ll just encounter an Cannot create an instance of "XyzView"… instead of the actual page content:

XAML editor error

 
 
 
 
 
 
 
 

The easiest workaround for this problem is to ensure that the VisibilityChanged event handler is not registered when viewing the page from within Visual Studio, but only at runtime. This can be done by checking whether the App is running in design mode using the DesignMode.DesignModeEnabled flag:

if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
	Window.Current.VisibilityChanged += OnVisibilityChanged;

Now you should be able to use the visual XAML editor as usual!

Permanent link to this article: http://www.mobilemotion.eu/?p=1329&lang=en

Older posts «