Wintellect Blogs

Linking Property Change Notifications in Xamarin Forms (or WPF/Silverlight)

Keith Rome

17 Oct , 2015  

I’d like to share a really awesome bit of code that I’ve been using in my XAML applications for a while now… there are many frameworks and examples out there, but I’ve not yet seen anyone else using this exact technique before…

MVVM in XAML UI Applications

If you are building app UIs using XAML, then you are more likely than not also using the MVVM design pattern. The general idea is that your code which handles application logic, business rules, etc. gets placed into ViewModel classes, and all visual widgets/controls get placed into XAML views. Typically we would have one View per ViewModel, but that’s not a requirement at all (more like a generalized observation), and in fact there are some situations where we might want to have multiple Views for the same ViewModel (or break a complex ViewModel into multiple parts while still connecting to a single View). The ViewModels are supposed to capable of standing alone, and we use data bindings and command bindings to connect the two. This way, we can unit test our ViewModels thoroughly, and (sometimes) allow UX designers to dictate the XAML layout directly.

That’s all fairly normal and typical.

As we dig a little more deeply into the mechanisms of data binding, we learn that part of the “magic” is achieved by way of the INotifyPropertyChanged interface (which includes only one thing – an event named PropertyChanged).… Read more

, , , ,

Wintellect Blogs

Model-View-ViewModel (MVVM) Explained

Jeremy Likness

24 Apr , 2014  

The purpose of this post is to provide an introduction to the Model-View-ViewModel (MVVM) pattern. While I’ve participated in lots of discussions online about MVVM, it occurred to me that beginners who are learning the pattern have very little to go on and a lot of conflicting resources to wade through in order to try to implement it in their own code. I am not trying to introduce dogma but wanted to pull together key concepts in a single post to make it easy and straightforward to understand the value of the pattern and how it can be implemented. MVVM is really far simpler than people make it out to be.

Why Even Care About MVVM?

Why should you, as a developer, even care about the Model-View-ViewModel pattern? There are a number of benefits this pattern brings to both WPF and Silverlight development. Before you go on, ask yourself:

  • Do you need to share a project with a designer, and have the flexibility for design work and development work to happen near-simultaneously?
  • Do you require thorough unit testing for your solutions?
  • Is it important for you to have reusable components, both within and across projects in your organization?
  • Would you like more flexibility to change your user interface without having to refactor other logic in the code base?
Read more

,

Wintellect Blogs

Understanding the Portable Library by Chasing ICommand (2 of 3)

Jeremy Likness

9 Mar , 2012  

Part 1: Creating the Portable Library
Part 2: Portability in Silverlight and WPF: a Tale of Type Forwarders (this post)
Part 3: Portability in Metro: A CLR and WinRT Love Affair

Portability in Silverlight and WPF: a Tale of Type Forwarders

In the last post, I walked through creating a portable assembly that will target Silverlight 4.0 and above, .NET Framework 4.5, and Windows 8 Metro. In the assembly were a few classes that handled commands and property change notification for a simple view model. In this post I’ll show you how to reference the assembly in Silverlight and WPF and explain why it works.

The first step is to create a new Silverlight 5.0 project (just using that because it’s the latest version, I know the library will technically support 4.0). Just make a simple application (no need to have a web project as well). The project will be created with the default App.xaml and MainPage.xaml. In the solution explorer, right-click on the References node and add a reference to the PortableCommandLibrary project. Now open up the XAML for the main page. At the top, add a namespace declaration for the view model:

xmlns:portable=”clr-namespace:PortableCommandLibrary;assembly=PortableCommandLibrary”

Next, paste the following XAML inside the main grid called LayoutRoot (you’ll use the exact same snippet for all of the projects in this series).… Read more

, , ,

Wintellect Blogs

Where’s my DataContext?

Sergio Loscialo

26 Jul , 2011  

Every now and then a question comes up concerning a missing DataContext.  The questions usually center around a ViewModel being set to a View properly, but then developer can not bind some command or property to a FrameworkElement.  And typically the FrameworkElement in question is nested within an ItemsControl’s ItemTemplate or other similar structure.

First things first, once a DataContext is set, it is available for every child and all nested children until another DataContext is set.  That’s why the following Xaml snippet works, and we don’t need to set the DataContext on both TextBlocks.

   1: <Grid DataContext="{StaticResource MyViewModel}">
   2:     <StackPanel>
   3:         <TextBlock Text="{Binding SomeText}" />
   4:         <TextBlock Text="{Binding SomeMoreText}" />
   5:     </StackPanel>
   6: </Grid>

This is basic data-binding and is at the heart of WPF, Silverlight and Windows Phone 7 development.  So, no matter how many elements we nest within the Grid, they all will have access to the DataContext until an element is assigned its own DataContext.

The question of the lost DataContext usually arises when the Xaml is slightly more complex.  For example,

   1: <Grid DataContext="{StaticResource MyViewModel}">
   2:     <ItemsControl ItemsSource="{Binding MyItems}">
   3:         <ItemsControl.ItemTemplate>
   4:             <DataTemplate>
   5:                 <Grid>
   6:                     <StackPanel Orientation="Horizontal">
   7:                         <TextBlock Text="{Binding MyItemText}" />
   8:                         <Button Content="Delete" Command="{Binding DeleteItemCommand}" />
   9:                     </StackPanel>
  10:                 </Grid>
  11:             </DataTemplate>
  12:         </ItemsControl.ItemTemplate>
  13:     </ItemsControl>
  14: </Grid>

This can tend to trip up developers new to WPF and Silverlight.  Why? 

The first reason is that Grid on line 5 has had its DataContext changed transparently; the DataContext of the ItemsControl is still MyViewModel, but the internal grid has its DataContext set to an object in the bound collection (seen in line 2 as the ItemsSource).  In other words, the DataContext of the grid inside the ItemTemplate is an instance of an object in the collection MyItems.  For the above binding to work, the objects in MyItems would need have a property named MyItemText and a property called DeleteItemCommand.… Read more

,

Wintellect Blogs

Auto-Discoverable Views using Fluent PRISM in Silverlight

Jeremy Likness

10 Jan , 2010  

One reason a developer would use a technology like MEF is to, as the name implies, make an application extensible through a process called discovery. Discovery is simply a method for locating classes, types, or other resources in an assembly. MEF uses the Export tag to flag items for discovery, and the composition process then aggregates those items and provides them to the entities requesting them via the Import tag.

Download the source code for this example

It occurred to me when working with PRISM and MEF (see the recap of my short series here) that some of this can be done through traditional means and I might be abusing the overhead of a framework if all I’m doing is something simple like marrying a view to a region.

Challenges with PRISM include both determining how views make it into regions and how to avoid magic strings and have strict type compliance when dealing with regions. This post will address one possible solution using custom attributes and some fluent interfaces.

Fluent Interfaces

Fluent interfaces simply refers to the practice of using the built-in support for an object-oriented language to create more “human-readable” code. It’s really a topic in and of itself, but I felt it made sense to simplify some of the steps in this post and introduce some higher level concepts and examples along the way.… Read more

, ,

Wintellect Blogs

PRISM, MEF and MVVM Part 1 of 3: Unity Glue

Jeremy Likness

21 Dec , 2009  

PRISM, also known as Composite WPF, has established itself as a very popular framework for building modular, scalable Silverlight applications. A newer contender, the Managed Extensibility Framework (MEF), has also grown in popularity. In fact, these two frameworks have left people scratching their heads wondering which one to use, when, how, and why.

Download the source code for this project.

Special note: the source won’t run “as is.” You need to take two steps: first, right click the PRISMMEF.Web project and choose, “set as start project.” Second, right click the PRISMMEFTestPage.aspx and choose “set as start page.” Then the project will run fine.

MEF will be packaged with Silverlight 4, and indeed has several preview releases available that will work on Silverlight 3 and 4. PRISM is coming out with newer releases that embrace the MEF framework. In fact, both frameworks work well together and know how to talk to each other’s containers.

In this series of posts I want to explore some concepts and aspects of solving the Silverlight application problem using both PRISM and MEF. I will use PRISM primarily for its ability to integrate views into regions, to dynamically load modules, and to provide an abstract messaging contract with the event aggregator.… Read more

, , , ,

Wintellect Blogs

New Version of Prism/Composite Application Guidance Released

Jeremy Likness

1 Nov , 2009  

For all of the Prism fans out there, a newer version has been released. You can download it here.

Jeremy Likness

Read more

,

Wintellect Blogs

A Twist on the Twist of the Observer Pattern

Jeremy Likness

26 Sep , 2009  

Thanks to those of you who read my Twist on the Observer pattern and gave me the feedback. You said,

“Hey, Jeremy, that’s neat, but there is already a pattern established for what you’re talking about, and a few great solutions ready to use. Besides, they are much, much more powerful…”

Thanks to Microsoft MVP Jason Rainwater for taking the time to give me an excellent explanation and for really delving into the inner workings of the solution.

The solution is the event aggregator pattern. For a good introduction, check out Jeremy Miller’s brain dump on the topic.

The PRISM/CAL comes with its own event aggregator. It supplies a IEventAggregator that you can wire into your dependency injection container, then reference throughout the project.

In my base service class (seen by all) I create an event like this:

...
public class EntitySelectedEvent : CompositePresentationEvent<MyEntity{
}
...

In the view model for the module that has to “wake up” when the entity is selected, I inject the aggregator into the constructor and then do this:

...
eventAggregator.GetEvent<EntitySelectedEvent().Subscribe(u=this.entity=u); 
...

When the entity is selected (in a completely different module), I can simply publish:

...
eventAggregator.GetEvent<EntitySelectedEvent().Publish(entity);
...

That’s it! One module listens for the selection and reacts, not caring where/who or how it is published (which means we can publish a test entity in our unit test and test the subscription mechanism) … while another module publishes the event and doesn’t care who is out there listening.… Read more

,

Wintellect Blogs

A Twist on the Observer Pattern

Jeremy Likness

23 Sep , 2009  

The observer pattern is well established and used. The typical scenario is to register to an class and then allow your Notify method to be called. This often involves keeping an internal list of observers and then iterating them to notify that something has changed. I had a situation recently that warranted a lighter weight approach that allows a many-to-many observation (multiple listeners, multiple objects to observe).

I was working with the Composite WPF/PRISM framework and had an interesting situation. One of my regions is implemented as a TabControl, so modules that register with the RegionManager inject their views into the tabs. This is a very powerful model because now I can add as many modules/views as I like and not worry about the implementation details of wiring up the tab control. I created a view interface IViewable to implement with my controls that exposes the name of the view along with a boolean indicating whether the view should be enabled (this allows me to restrict going to certain tabs if they depend on data from another tab).

The issue was figuring out the best way to handle the tab focused event. By default, the views are wired up and ready to go when you click the tab.… Read more

, ,

Wintellect Blogs

Editing WPF Controls in Expression Blend

Jeremy Likness

20 Sep , 2009  

This is one of those quirks that until you try it, you may not know it exists or what the answer is.

I am working on a WPF project and have a separate control library (actually, a module because I am using the Component Application Guidance/PRISM pattern). I pulled it into Expression Blend and was surprised to see that I had no “design” view. The option simply didn’t exist/was grayed out in the menu.

So, I did some digging around and it turns out that because my controls file is just a C# class library, Expression doesn’t know it is “allowed” to design the controls. To tell it this, you simply need to open your .csproj file that the XAML is in, then add this to the first PropertyGroup tag that you find:

<PropertGroup...
<ProjectTypeGuids{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids...
</PropertyGroup

Just enter it exactly with the same Guids … now close out of Expression, reload, and voila! you can now design.

Jeremy Likness

Read more