Archives for : April2014

Observer and Command Design Patterns – A Real World Example

Up next in my series on ways you’ve probably used design patterns in real-life and may not have even known it, the Observer and Command design patterns. This continues on from my post Composite and Memento Design Patterns – A Real World Example. Command pattern is meant to actually decouple the GUI and back-end code. It may seem like using an event and executing a command are the same things, and as we are using them here they are pretty close.

XAML for this post

<Window x:Class="CompositeMementoSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <ListView Grid.Row="0" MinWidth="150" ItemsSource="{Binding CompositeList}" />
        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <Button Click="AddFiles">Add Files</Button>
            <Button Command="{Binding SaveXmlCommand}">Save XML</Button>
            <Button Command="{Binding LoadXmlCommand}">Load XML</Button>
        </StackPanel>
    </Grid>
</Window>

Looking at the button where we add files you can see clearly the “Click” event. Again, what that does is register our code-behind as a listener such that when the click event is fired on the button the event is called. But how do we generate unit tests for this? Well, let’s look at the event.

Click event for AddFiles in the code-behind

private void AddFiles(object sender, RoutedEventArgs e)
{
	FileGroupViewModel vm = (FileGroupViewModel)DataContext;
	OpenFileDialog ofd = new OpenFileDialog();
	ofd.Filter = vm.Model.OpenFileDialogFilter;
	ofd.Multiselect = true;

	if (ofd.ShowDialog() != true)
		return;

	vm.AddFiles(ofd.FileNames);
}

ObserverWe can see here that the AddFiles exists in the view model and provides a way for us to get from the view to the view model.  In standard GUI code-behind we create the button and add a “Click” event. This is part of the observer design pattern, where the code-behind is registered as a listener and gets notified any time the button is clicked.  Observer pattern is kind of like, “Tell me what to call (aka notify) when I’ve been clicked and I’ll do it.”

Okay, cool, but, well, this isn’t very MVVMy. MVVM likes to bind everything to properties. If you look at the “Save XML” button and the “Load XML” button, that is exactly what we are doing.  Command pattern works by saying, “hey, you, command there, when I do my click, you execute whatever it is you are supposed to do.”

Notice that this is different from observer.  I know the differences may seem pretty minor, and they really are, but they are also important. In the code-behind above there is still a dependency between the view and the view model. There still has to be this AddFiles event that calls the view models AddFiles. That means there is code that we can’t test against without instantiating the view. In the example here the code bit is fairly small but it still is code that isn’t being tested in a unit test. In command, because the command is looking for the action to happen rather then waiting to be told that it has happened the dependencies are opposite.Command

Now we have to get a bit off track here as we look at the SaveXmlCommand and the LoadXmlCommand.  We don’t want to create a SaveFileDialog and an OpenFileDialog in our view model. The view model is not a view, so we shouldn’t be creating elements that affect the UI there. So I have two separate classes that implement the below ISaveDialog and IOpenDialog interfaces that are a part of my views.  Then on my constructor I take the services that implement the interface and use them when the commands are called.

public interface ISaveDialog
{
	string Filter { get; set; }
	string SaveFileName { get; set; }
	bool? ShowSaveFileDialog();
}

public interface IOpenDialog
{
	string Filter { get; set; }
	string OpenFileName { get; set; }
	bool? ShowOpenFileDialog();
}

And finally we get to the guts of my FileGroupViewModel

IOpenDialog OpenDialogService;
ISaveDialog SaveDialogService;

public FileGroupViewModel(IOpenDialog OpenDialogService, ISaveDialog SaveDialogService)
{
	this.Model = new FileGroupModel();
	this.OpenDialogService = OpenDialogService;
	this.SaveDialogService = SaveDialogService;

	OpenDialogService.Filter = model.OpenFileDialogFilter;
	SaveDialogService.Filter = model.OpenFileDialogFilter;

	saveXmlCommand = new DelegateCommand(SaveXml, CanSaveXml);
	loadXmlCommand = new DelegateCommand(LoadXml);
}

public void AddFiles(string[] FileNames)
{
	foreach (string path in FileNames)
	{
		if (path.EndsWith(Model.SerializedExtension))
		{
			try
			{
				FileGroupModel fgm = FileGroupModel.ReadFromFile(path);
				if (fgm != null)
				{
					if (string.IsNullOrEmpty(fgm.Name))
					{
						fgm.Name = System.IO.Path.GetFileNameWithoutExtension(path) + " (" + path + ")";
					}
					Model.Groups.Add(fgm);
					continue;
				}
			}
			//if we get an exception assume it's not a FileGroupModel and add as a regular file
			catch { }
		}
		Model.Files.Add(new System.IO.FileInfo(path));
	}
}

DelegateCommand saveXmlCommand;
public ICommand SaveXmlCommand
{
	get { return saveXmlCommand; }
}

bool CanSaveXml()
{
	return Model.CompositeList.Count > 0;
}

void SaveXml()
{
	if (SaveDialogService.ShowSaveFileDialog() != true)
		return;

	Model.WriteToFile(SaveDialogService.SaveFileName);
}

DelegateCommand loadXmlCommand;
public ICommand LoadXmlCommand
{
	get { return loadXmlCommand; }
}

void LoadXml()
{
	if (OpenDialogService.ShowOpenFileDialog() != true)
		return;

	FileGroupModel newModel = FileGroupModel.ReadFromFile(OpenDialogService.OpenFileName);
	if (newModel == null)
		return;

	Model = newModel;
}

What we can do here is that when creating our unit tests we can fake an ISaveDialog and an IOpenDialog that could return true or false on their respective show methods depending on what we are testing.

Now, I have to wade a bit further into the weeds here. This isn’t really the way I would implement this in a production application. One of the problems with MVVM is that views and view models tend to be classes unto themselves that don’t deal with anything else, just themselves. Models will get referenced all over but not necessarily views and view models.

A lot of blogs, like mine, tend to sometimes do things a bit off in the interest of brevity. A lot of what is here in this post, if you’ve read my past series on MVVM, you’ve already seen. The purpose here was that I wanted to talk about the differences between Command and Observer design patterns. The differences are important and I hope I’ve gotten across to you why it is best to use Command in an MVVM development environment.

How to do it more right

So how would I implement something like this in a production application? Think about the Cut command (of Cut/Paste fame). Anywhere in a UI I should be able to add a cut command. I want to be able to have it in my Edit menu, I want to be able to have it in my context menu, I want to be able to put it as a button on my toolbar and finally I want to bind a key command to it. In standard code-behind each button click would have to implement some click event in which it has to then figure out what to do. There is a huge potential for a lot of duplication of code as well as a lot of code that may not be subjected to a unit test. The solution in MVVM is to use a library like Unity where you can register global commands to handle this exact situation. Unity is outside of the scope of this post but I encourage you to find out more about it. I may even do a series on unity.

I know at first MVVM seems like a massive headache (and it can be). It seems like there is so much extra crap you have to add on. But if you can hang on long enough to get through the crap I think you’ll find that you have better, sounder, more stable applications.

Thanks,
Brian

Image Credits:
Observer
Command

Icons in Modern UI (with a nod to UX)

I was battling with some icons this weeks so I figured I’d pass on some of my general experience in this area. I’ll hold off on the sample of the command pattern for next week.

Let’s make sure we get the terminology correct, what Microsoft once labeled “Metro UI” is now called “Modern UI”, which is the Windows 8 Surface UI for Windows Runtime (aka Windows RT) apps. It was a lot easier when they just called everything Metro UI.

First off, I’m not a graphics designer or UX expert. I’m a software engineer. My degree is in computer science, not graphics design. As a whole we, and yes, I’m sure I probably mean you too, software engineers design user interfaces poorly. Sometimes downright horribly. But not all software companies have graphics designers or UX experts on staff (which I consider a shame). Not all clients want to pay for UX work (which is doing themselves a disservice). So I’ve had to fill in for the role of both graphics designer and UX expert many times.

I try and keep up with the latest releases in the Microsoft ethos as it relates to .NET but I also try to round off my rough edges with some UX reading. I know this doesn’t make me a UX expert by any stretch of the imagination. But it does make me just slightly more competent this area. Also, since I do a lot of UI work, having a general understanding of UX I feel is necessary for me to competently do my job. Little things like “error messages should be apologetic” and “where there is both an icon and text, the icon should come first” end up making a big difference to a good UI.

Getting Started in UX

If you are interested in UX I would recommend starting with the Microsoft UX guidelines for Windows Runtime apps. After you’ve digested that thriller, try doing some reading on ux.stackexchange.com. After that you can start in on some industry sites like UX Magazine.

On To Icons

The Microsoft UX guidelines above recommend using the Segoe UI font for Windows 8 development, but there is a brother font, Segoe UI Symbol, that provides a huge number of potiential icons. To look at all the images I would recommend using the Word Insert Symbol tool in Word if possible as there seems to be quite a few more symbols available than what’s in Character Map.InsertSymbol

Choosing the magnifying glass you can use the following code for a search button:

<Button Margin="0 0 5 0" Width="16" Height="16" FontFamily="Segoe UI Symbol" Opacity=".75" Command="{Binding SearchCommand}" ToolTip="Search" Style="{DynamicResource SearchStyle}" Content="🔎" />

Note that if you are in FF or IE the magnifying glass should show up correctly but in Chrome it shows up as a box. These icons are really just Unicode but with Segoe UI Symbol they look like they are a part of Modern UI.

My final search control ended up looking like:SearchBar

which looks great since by using the font directly you get to take advantage of the TrueType nature of the font, which means it’s vector based and always scales in size. 

Okay, hundreds of icons at your finger tips, but what if that’s not enough?  What do you do if you can’t find what your looking for?  Head over to Modern UI Icons. As of right now, 1229 icons, nearly all of which are Creative Commons, that you can use however you want. Make sure you read the license as not all of them are CC, but by far the vast majority of them are. And they look like icons you would use in Modern UI, just like they should.

All the icons are available as images in both light and dark themes, as well as xaml and svg so you can use them as vectors.

appbar.input.keyboard
appbar.input.keyboard
<?xml version="1.0" encoding="utf-8"?>
<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="appbar_input_keyboard" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
	<Path Width="50.6667" Height="28.5" Canvas.Left="12.6667" Canvas.Top="23.75" Stretch="Fill" Fill="#FF000000" Data="F1 M 15.8333,23.75L 60.1667,23.75C 61.9156,23.75 63.3333,25.1678 63.3333,26.9167L 63.3333,49.0833C 63.3333,50.8322 61.9156,52.25 60.1667,52.25L 15.8333,52.25C 14.0844,52.25 12.6667,50.8322 12.6667,49.0833L 12.6667,26.9167C 12.6667,25.1678 14.0844,23.75 15.8333,23.75 Z M 17.4167,28.5L 17.4167,47.5L 58.5833,47.5L 58.5833,28.5L 17.4167,28.5 Z M 20.5833,30.0834L 28.5,30.0833L 28.5,38L 20.5833,38L 20.5833,30.0834 Z M 30.0833,30.0833L 36.4166,30.0834L 36.4166,38L 30.0833,38L 30.0833,30.0833 Z M 20.5833,39.5834L 28.5,39.5833L 28.5,45.9167L 20.5833,45.9167L 20.5833,39.5834 Z M 30.0833,39.5833L 45.9167,39.5834L 45.9167,45.9167L 30.0833,45.9167L 30.0833,39.5833 Z M 38,30.0834L 45.9167,30.0833L 45.9167,38L 38,38L 38,30.0834 Z M 47.5,30.0833L 55.4167,30.0833L 55.4167,38L 47.5,38L 47.5,30.0833 Z M 47.5,39.5834L 55.4167,39.5833L 55.4167,45.9167L 47.5,45.9167L 47.5,39.5834 Z "/>
</Canvas>

That’s it for now.  Thousands of icons you may not have known you had easy (and free) access to.

 

Thanks,
Brian

 

Image Source:
appbar.input.keyboard, Modern UI Icons

So you don’t need to know software design patterns. But, as I hope got across in my post, knowing and understanding patterns can only benefit you. I wanted to put together a real-life example of some of the instances where I’ve used patterns, even if the use of the patterns was unintentional. Hopefully you will get some use out of them.

I had a requirement where I had to track a list of files and needed to be able to save this list. But the list needed to be able to not only have a list of files but needed to support a list of lists. The use case was that the user could define a list of files say, “My files from client A.” The user could then put together a list of lists defined as, “My clients from the east coast” which would be comprised of lists from any clients on the east coast.

Of course this defines the composite pattern. The composite pattern is just an object that contains zero or more of that object. The two most obvious classes in .NET that use this are TreeViewItem and MenuItem. A MenuItem contains it’s own content as a MenuItem but also contains children MenuItems. In my case my class, “FileGroupModel” has a list of files (think of that list as the content of the class) as well as a list of FileGroupModels, which is exactly what the composite design pattern is.

Now to facilitate this I obviously need to save out the FileGroupModel, which is the memento pattern. As you’ll see in the code I went with a DataContract to save out the data.

using CompositeMementoSample.Infrastructure;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace CompositeMementoSample.Models
{
    [DataContract(IsReference = true)]
    public class FileGroupModel : DomainObject
    {
        public virtual string OpenFileDialogFilter 
        {
            get { return "Files & Groups (*.*)|*.*|File Groups (*.fxml)|*.fxml"; }
        }
        public virtual string SerializedExtension 
        {
            get { return ".fxml"; }
        }

        [DataMember]
        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                if (this.name != value)
                {
                    this.ValidateProperty("Name", value);
                    this.name = value;
                    this.RaisePropertyChanged("Name");
                }
            }
        }

        [DataMember]
        private ObservableCollection<FileInfo> files;
        public ObservableCollection<FileInfo> Files
        {
            get
            {
                return files;
            }
        }

        [DataMember]
        private ObservableCollection<FileGroupModel> groups;
        public ObservableCollection<FileGroupModel> Groups
        {
            get
            {
                return groups;
            }
        }

        public ReadOnlyCollection<object> CompositeList
        {
            get
            {
                List<object> allItems = new List<object>();
                allItems.AddRange(files);
                allItems.AddRange(groups);
                return new ReadOnlyCollection<object>(allItems);
            }
        }

        public FileGroupModel()
        {
            files = new ObservableCollection<FileInfo>();
            files.CollectionChanged += child_CollectionChanged;
            groups = new ObservableCollection<FileGroupModel>();
            groups.CollectionChanged += child_CollectionChanged;
        }

        void child_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            this.RaisePropertyChanged("CompositeList");
        }

        public void WriteToFile(string Path)
        {
            using (MemoryStream memStm = new MemoryStream())
            using (StreamWriter outfile = new StreamWriter(Path))
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(FileGroupModel));
                ser.WriteObject(memStm, this);
                memStm.Seek(0, SeekOrigin.Begin);
                string result = new StreamReader(memStm).ReadToEnd();
                outfile.Write(result);
            }
        }

        public static FileGroupModel ReadFromFile(string Path)
        {
            string contents = System.IO.File.ReadAllText(Path);
            using (Stream stream = new MemoryStream())
            {
                byte[] data = System.Text.Encoding.UTF8.GetBytes(contents);
                stream.Write(data, 0, data.Length);
                stream.Position = 0;
                DataContractSerializer deserializer = new DataContractSerializer(typeof(FileGroupModel));
                object o = deserializer.ReadObject(stream);
                return o as FileGroupModel;
            }
        }

        public override string ToString()
        {
            return Name;
        }
    }
}

To start with, FileGroupModel extends DomainObject which in turn implements INotifyPropertyChanged and INotifyDataErrorInfo. This is done so that the model can integrate into MVVM. DomainObject can be found in my series on MVVM. So the MVVM stuff out of the way, we can get on to the composite design pattern.

Implementing Composite

Looking at line 42 you can see the observable collection that contains our FileInfos. At line 52 you can see the observable collection that contains our FileGroupModels, which makes this the composite pattern.  That’s it.  The composite pattern is just about implementing tree structure data.

CompositeMementoBut we need to use this in MVVM and we can only to bind an ItemsSource to one list. That is the purpose of the CompositeList. By hooking into the CollectionChanged event of the two observable collections, anytime files or file group models are added to either list we can raise a property changed event so the view way down the link that gets hooked up to the model via the view model, can get notified of the change to the collection.  My use of naming the combined list “CompositeList” is a bit unfortunate as I obviously mean that to indicate a combined list and not anything that really has to do with the composite pattern.

Implementing Memento

The last requirement is to be able to save out the state of the object (i.e. the memento design pattern). In .NET, arguably, the two easiest ways to write out an object is BinaryFormatter and DataContract. I tend to only use the binary formatter if there is proprietary data that needs to be stored. When that’s the case I use not only the BinaryFormater but I use it with a CryptoStream to ensure the security of the data. Most of the time, however, I try to use a DataContractSerializer. It’s a bit more in the set-up, having to define the DataContract and DataMember attributes but on the whole everything seems a bit cleaner. That way, if I need to, I can read the XML directly and see what’s going on with the data.

Now the tough part is that if you are going to use multiple classes that extend from a base class then you have to violate the Open-Closed principle. In my use of the above class I actually extend FileGroupModel (which is an abstract in my production code) to limit the types of files that are embedded. The problem with this approach is that you have to define a KnownType attribute in the base class so when you deserialize the object the DataContractSerializer knows what to do with it. This means that every time you add a class that extends the base class you have to add a KnownType for that class in the base. See? An obvious violation of the OCP but definitely a situation where we can ignore the rules on the paint can.

Next week I’ll follow up this post with an MVVM sample that is a bit closer to how I actually use it. I’ll show a sample extending FileGroupModel so you can get a better idea of using DataContractSerializer, but this also leads into using the command design pattern.

Thanks,
Brian

Binding a Dependency Property of a View to its ViewModel

UPDATE 07/30/2014:
Please be sure to check out the second part to this at Binding a Dependency Property of a View to its ViewModel, part Deux which contains a working sample solution of the code here.

I like MVVM in concept and I had prepared a long, off-topic rant about MVVM because of a bit of trouble I’m having with it at the moment.  I deleted it, however.  Maybe I’ll make it an on-topic post at some point in the future.  Regardless, one of the issues I had was I needed to make a user control that could not only be the primary control of a view but I needed it to be a child control of another view.  There are a lot of complex operations that the view model controls in terms of handling states and progress bars.  It made sense, therefore, when I needed almost the exact same operations but with four different classes that inherit from the same model to use the same view.

To do this I needed a way to define a “ViewMode” of the user control.  For the default view where it would be the full version of the control the mode would be “Full” and for where I was using it as a child control the mode would be “Compact”.    Given that I think one of the things we should strive for is re-use it seemed like this should be an easy problem.  After some googling around though the general consensus seemed to be that you should just incorporate this into your new view model.  This just seems stupid to me.

Not about incorporating it into the view model.  That much is obvious but that there wasn’t some easy, obvious solution on how to bind a dependency property to a property in the view model.  Fortunately my StackOverflow foo seemed to be working with me and I found the right answer.

You have to manually bind your dependency property to the property on your view model.  It should have been obvious and I’m not sure why I hit on so many wrong answers but here is my solution:

Add the dependency property to MyView that will bind to the view model

public ViewMode ViewMode
{
	get { return (ViewMode)GetValue(ViewModeProperty); }
	set { SetValue(ViewModeProperty, value); }
}

public static readonly DependencyProperty ViewModeProperty =
	DependencyProperty.Register("ViewMode", typeof(ViewMode), typeof(MyView), new PropertyMetadata(ViewMode.Full));

I’ve defined an enum “ViewMode” that has two values, “Full” and “Compact” and I utilize it here.

Then in the ctor of MyView I have

public MyView()
{
	InitializeComponent();

	//http://stackoverflow.com/questions/15132538/twoway-bind-views-dependencyproperty-to-viewmodels-property
	string propertyInViewModel = "ViewMode";
	var bindingViewMode = new Binding(propertyInViewModel) { Mode = BindingMode.TwoWay };
	this.SetBinding(ViewModeProperty, bindingViewMode);
}

This manually sets the binding to a property “ViewMode” that is in my view model. So “ViewMode” exists in both the view and the view model and the manual binding will keep everything in sync.

In my XAML where I use the control as a stand-alone view the XAML looks like

<views:MyView Grid.Row="1" Margin="50" />

and in my XAML where I use the control as a child control the XAML looks like

<views:MyView Grid.Row="0" Grid.Column="0" ViewMode="Compact" />

MMVVVMVMI have also added some converters to help that bind the visibility of controls to the “ViewMode” of the view model. Now I have to point out that what I need to show and/or hide based on the ViewMode was fairly minimalistic. It might make more sense to have different control but in my case it made more sense to use the same control.

This is great and allows us to customize the view based on the ViewMode, but it doesn’t keep MyParentViewModel of the parent control in sync with MyViewModel of the child control when it’s being used as a child control. To do this we need to add another dependency property in MyView and bind it like we did the ViewMode. Then in MyParentView we have to bind that property to the property of MyParentViewModel in XAML.  The kind of crappy part is there is some manual work you have to do to make this work right.  Not only that but the binding works out to be fairly ugly.

The view model of “MyViewModel” looks like:

class MyViewModel
	ViewMode ViewMode
	ObjectGroup ActiveObject

The view model of “MyParentViewModel” looks like:

class MyParentViewModel
	ObjectGroup ActiveObjectOne
	ObjectGroup ActiveObjectTwo
	ObjectGroup ActiveObjectThree
	ObjectGroup ActiveObjectFour

In “MyView” I add the following dependency property:

public ObjectGroup ActiveObject
{
	get { return (ObjectGroup)GetValue(ActiveObjectProperty); }
	set { SetValue(ActiveObject, value); }
}

public static readonly DependencyProperty ActiveObjectProperty =
	DependencyProperty.Register("ActiveObject", typeof(ObjectGroup), typeof(MyView), new FrameworkPropertyMetadata(null, OnActiveObjectChanged));

private static void OnActiveObjectChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
	((MyViewModel)((MyView)d).DataContext).ActiveObject = (ObjectGroup)e.NewValue;
}

which is incredibly ugly. The problem is that when I do the binding on the dependency it directly calls SetValue and ignores my setter. As such I have to set things up with the property changed call-back to make everything tie together correctly.

Unfortunately I still need to add the manual binding to my view

propertyInViewModel = "ActiveObjectGroup";
var bindingActiveObjectGroup = new Binding(propertyInViewModel) { Mode = BindingMode.TwoWay };
this.SetBinding(ActiveObjectGroupProperty, bindingActiveObjectGroup);

Okay, so now everything works correctly right? Nope. The problem is that the binding on MyView sees the local data context, not the binding I want to give the control from MyParentView. As such I need to play with the binding to make sure we’re all on the same page.

The XAML basically ends up looking like

<UserControl x:Class="MyParentView">
	<UserControl.DataContext>
		<viewModels:MyParentViewModel />
	</UserControl.DataContext>
	<Grid>
		<Grid.RowDefinitions>
			<RowDefinition />
			<RowDefinition />
			<RowDefinition />
			<RowDefinition />
    		</Grid.RowDefinitions>
		<views:MyView Grid.Row="0"
				 ViewMode="Compact" 
				 ActiveObject="{Binding DataContext.ActiveObjectOne, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
		<views:MyView Grid.Row="1"
				 ViewMode="Compact" 
				 ActiveObject="{Binding DataContext.ActiveObjectTwo, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
		<views:MyView Grid.Row="2"
				 ViewMode="Compact" 
				 ActiveObject="{Binding DataContext.ActiveObjectThree, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
		<views:MyView Grid.Row="3"
				 ViewMode="Compact" 
				 ActiveObject="{Binding DataContext.ActiveObjectFour, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
	</Grid>
</UserControl>

MMVVVMVM2What we’re doing here is changing the default “ActiveObject” in the child control from the one created by its view model to the one created by the parent view model. This way everything is in sync due to the bindings we created in the constructor of “MyView”.

When I bind like I do above the ObjectGroup instances from MyParentViewModel end up being the same as the instance of ObjectGroup in the MyViewModel.

The cool thing about all this is that I can create a new instance of MyParentViewModel as needed and it will set everything up as it should.

And that’s it. Maybe this is one of those answers that is so obvious no one felt the need to write about it. Or maybe everyone’s found the same answer I did. Or maybe this is the wrong approach. After all, it’s not very “MVVM-like”, having to manually create the bindings and then having to manually set the ActiveObject in the dependency property. If you know of a better way to do this let me know.

Thanks,
Brian