DaedTech

Stories about Software

By

WPF Combo Boxes

I thought I’d put together a quick post today on something that annoyed me and that I found unintuitive: binding with the WPF combo box. I’m doing some development following MVVM, and a situation came up in which I had a view model for editing a conceptual object in my domain. Let’s call it a user for the sake of this post, since the actual work I’m doing is nominally proprietary.

So, let’s say that user has a first name and a last name and that user also has a role. Role is not an enum or a literal, but an actual, conceptual reference object. In the view model for a customer edit screen, I was exposing a model of the user domain object for binding, and this model had properties like first name and last name editable via text box. I now wanted to add a combo box to allow for editing of the role by selecting one choice from a list of valid roles.

Forgetting the code for the presentation tier, I did this in the XAML:


Now, I’ve had plenty of occasions where I’ve exposed a list from a view model and then a separate property from the view model called “Selected Item.” This paradigm above would faithfully set my SelectedItem property to one of the list members. But here, I’m doing something subtly different. The main object in the view model–its focus–is UserModel. That is, the point of this screen is to edit the user, not roles or any other peripheral data. So, what I’m actually doing here is trying to bind a reference in another object to one of the items in the list.

What I have above didn’t work. And after a good bit of reading and head scratching, I figured out why. SelectedItem tries to find whatever it’s bound to in the actual list. In the case where I have a list in my view model and want to pick one of the members, this is perfect. But in the case where the list of roles contains objects that are distinct from the user’s role reference, this doesn’t work. The reason it doesn’t work, I believe, is that SelectedItem operates on equality. So if I were to create a list of roles and then assign one of them to the user model object, everything would be fine, since object equals defaults to looking for identical references. But in this case, where the list of roles and the user’s role are created separately (this is done in the data layer in my application) and have nothing in common until I try to match my user role to the list of roles, reference equals fails.

As an experiment, I tried the following:

public class Role
{
  public int Id { get; set; }
  
  public override bool Equals(object obj)
  {
    return Equals(obj as Role);
  }

  public bool Equals(Role role)
  {
    return role != null && role.Id == Id;
  } 
}

After I put this code in place, viola, success! Everything now worked. The combo box was now looking for matching IDs instead of reference equals. I packed up and went home (it was late when I was doing this). But on the drive home, I started to think about the fact that two roles having equal IDs doesn’t mean that they’re equal. ID is an artificial database construct that I hide from users for identifying roles. ID should be unique, and I have a bunch of unit tests that say that it is. But that doesn’t mean that equal IDs means conceptual equality. What if I somehow had two roles with the same ID but different titles, like, say, if I was allowing the user to edit the role title. If for some reason I wanted to compare the edited value with the new one using Equals(), I wouldn’t want the edited and original always to be equal simply because they shared an ID.

I figured I could amend the equals override, but I’m not big on adding code that I’m not actually using, and this is the only place I’m using Equals override. So I went back to the drawing board and read a bit more about the combo box. What I discovered was a couple of additional, rather unfortunately named properties: SelectedValue and SelectedValuePath. Here is what the amended working version looked like without overriding Equals:


ItemsSource is the same, but instead of a SelectedItem, I now have a “SelectedValue” and a “SelectedValuePath”. SelectedValue allows you to specify the binding target by a property of it, and SelectedValuePath allows you to specify which property of the members of ItemsSource should match SelectedValue.

So what the above is really saying is “I have a list of Roles. The role that’s selected is going to be whichever role in the list has an ID property that matches UserModel’s role ID.” And by default, when you change which value is selected, the UserModel’s “RoleId” gets updated with the new selection.

This actually somewhat resembles what I remember from doing Spring and JSP many moons ago, but there’s a little too much rust and probably too many JDKs and whatnot released between then and now for me to know that it’s current. When you actually get down to the nitty gritty of what’s going on, it is intuitive here. I just think the control’s naming scheme is a bit confusing. I would prefer something that indicated the relationship between the item and the list.

But I suppose lack of familiarity always breeds confusion, which in turn breeds frustration. Maybe now that I took the time to understand the nitty gritty instead of just copying what had worked for me in previous implementations, I’ll warm up to the naming scheme.

By

MVVM and Dialogs

For those familiar with the MVVM (Model, View, View-Model) pattern in .NET development, one conundrum that you’ve probably pondered, or at least read about, is what to do about showing a dialog. For a bit of background, MVVM is centered around the concept of binding from the View (XAML markup) to the “ViewModel”, which essentially acts as a staging platform for UI binding.

The ViewModel exposes the “Model” in such a way that the XAML can passively bind to it. It does this by exposing bindable properties (using INotifyPropertyChanged) and bindable commands (by using ICommand). Properties represent data, and commands represent actions.

The Problem

So, let’s say that you want a clean MVVM implementation which generally aspires to have no code-behind. Some people are more purist about this than others, but the concept has merit. Code-behind represents an active way of binding. That is, you have code that knows about the declarative markup and manipulates it. The problem here is that you have a dependency bugaboo. In a layered application, the layers should know about the one (or ones) underneath them and care nothing about the ones above them. This allows a different presentation layer to be plopped on a service tier or a different view to be skinned on a presentation tier. In the case of code-behind, what you have is a presentation tier that knows about its view and a view that knows about its presentation tier. You cannot simply skin another view on top because the presentation tier (read: code-behind) expects named elements in the declarative markup.

So, in a quest to eliminate all things code behind, you adopt MVVM and do fine when it comes to data binding and basic commands. But inevitably you want to open a window, and the WPF framework is extremely clunky and win-forms-like when it comes to this. Your choices, out of the box, are to have a named element in the XAML and manipulate it to show a dialog or else to have an event handler in the code behind.

What Others Have Suggested

The following are suggestions I’ve seen to address this problem and the reasons that I didn’t particularly care for them, in regards to my own situation. I did a fair amount of research before rolling my own.

  1. Just use the code behind (second response to post (3), though I’ve seen the sentiment elsewhere). I don’t really like this because I think that, when it comes to design guidelines, slippery slopes are a problem. If you’re creating a design where you’d like to be able to arbitrarily swap out groups of XAML files above a presentation layer, making this exception is the gateway to your skinnable plans going out the window. Why make exceptions to your guidelines if it isn’t necessary?
  2. Mediator Pattern. Well, this particular implementation lost me at “singleton,” but I’m not really a fan of this pattern in general for opening windows. The idea behind all of these is to create a situation where the View and ViewModel communicate through a mediator so as to have no direct dependencies. That is, ViewModel doesn’t depend on View–it depends on Mediator, as does the View. Generally speaking, this sort of mediation is effective at allowing tests and promoting some degree of flexibility, but you still have the same dependency in concept, and then you have the mediator code to maintain and manage.
  3. Behaviors. This is a solution I haven’t looked at too much and might come around to liking. However, at first blush, I didn’t like the looks of that extra XAML and the overriding of the Behavior class. I’m generally leery of .NET events and try to avoid them as much as possible. (I may create a post on that in and of itself, but suffice it to say I think the syntax and the forced, weakly typed parameters leave a lot to be desired.)
  4. Some kind of toolkit Blech. Nothing against the people that make these, and this one looks pretty good and somewhat in line with my eventual situation, but it seems like complete overkill to download, install, and maintain some third party application to open a window.
  5. IOC Container. I’ve seen some of these advertised, but the same principle applies here as the last one. It’s overkill for what I want to do.

I’ve seen plenty of other solutions and discussion as well, but none of them really appealed to me.

What I Did

I’ll just put the code and example usage in XAML here and talk about it:

public class OpenWindowCommand : SimpleCommand where T : Window, new()
{
    #region Fields

    /// Stores the function that evaluates whether or not the command can be executed
    private readonly Func _canExecute;

    /// View model that will serve as data context of the command in question
    private readonly IViewModel _viewModel;

    /// Used to verify method preconditions and object invariants
    private readonly ArgumentValidator _validator = new ArgumentValidator();
                                                                               

    #endregion

    #region Constructor

    /// For window open command, 
    /// 
    public OpenWindowCommand(IViewModel viewModel, Func canExecute = null) : base(canExecute, null)
    {
        _validator.VerifyNonNull(viewModel);

        _viewModel = viewModel;
    }

    #endregion

    #region ICommand stuff

    /// Ignores the command parameter, creates the window, sets its datacontext, and shows
    public override void Execute(object parameter)
    {
        var myWindow = new T();
        myWindow.DataContext = _viewModel;
        myWindow.ShowDialog();
    }

    #endregion
}

    

That’s it. The things that are referenced here that you won’t have are worth mentioning but not vital to the implementation. SimpleCommand, from which “OpenWindowCommand” inherits, is a class that allows easier command declaration and use. It implements ICommand. It takes a delegate or a boolean for CanExecute() and a delegate for execution (that we override in OpenWindowCommand since we have a concrete implementation). Simple command is not generic–the generic is in OpenWindowCommand to allow strongly typed window opening (the presumption here being that you want to use this for windows that you’ve created and want to show modally).

The binding in the XAML to commands is to an object that represents a collection of commands. I actually have a CommandCollection object that I’ve created and exposed as a property on the ViewModel for that XAML, but you could use a Dictionary to achieve the same thing. Basically, “Commands[]” is just an indexed hash of commands for brevity in the view model. You could bind to a OpenWindowCommand property on your ViewModel.

So, basically, when the view model from which you want to open a window is being setup, you create an instance of OpenWindowCommand(YourViewModelInstance). When you do this, you passively expose a window open for binding. You’re saying to the view “execute this command to open window of type X with view model Y for backing.” Your view users are then free to bind to this command or not.

Why I Like This

First of all, this implementation creates no code-behind. No named windows/dialogs certainly, but also no event handlers. I also like that this doesn’t have the attendant complexity of most of the other solutions that I’ve seen. There’s no IMediator/Mediator, there’s no ServiceLocator, no CommandManager.Instance–none of it. Just one small class that implements one framework interface.

Naturally, I like this because this keeps the ViewModel/presentation layer View agnostic. This isn’t true out of the box here, but it is true in my implementation. I don’t declare commands anywhere in my ViewModels (they’re all wired in configurably by my home-rolled IOC implementation at startup). So the ViewModel layer only knows about the generic Window, not what windows I have in my view.

Room for Improvement

I think it would be better if the presentation tier, in theory, didn’t actually know about Window at all. I’m keeping my eyes peeled for a way to remove the generic parameter from the class and stick it on the Execute() method to be invoked from XAML. XAML appears to be very finicky when it comes to generics, but I have some hope that this may be doable in the latest release. I’ll re-post when I find that, because I’d love to have a situation in which the XAML itself could specify what kind of window to open as a command parameter. (I’m not in love with command parameters, but I’d make an exception for this flexibility.)

I’m also aware that this doesn’t address non-modal windows, and that there is currently no mechanism for obtaining the result from ShowDialog. The former I will address as I grow the application that I’m working on. I already have a solution for the latter in my code, and perhaps I’ll detail that more in a subsequent post.

By

DXCore Plugin Part 3

In a previous post, I mentioned my ongoing progress with a DX Core plugin. I’d been using it successfully for some time now but had to dust it off again last week. Another convention that I’m required to abide for consistency sake but don’t much care for is explicit typing of my variables.

That is, I prefer declarations like:

var myTypeWithLongName = new TypeWithALongName();

rather than:

TypeWithALongName myTypeWithLongName = new TypeWithALongName();

I personally find the second to be needlessly syntactically noisy, and I don’t really see any benefit since the implicit (var) typing preserves strong typing and even causes the resulting type to show up in Intellisense. But, when in Rome…

Compared to my previous setup, this was relatively straightforward. Initially, I thought it would be even simpler than it turned out to be, since Code Rush itself supports the explicit/implicit conversion as an individual refactoring. I figured I’d just have to iterate through the file and call something like “Some.CodeRush.Namespace.MakeExplicit(myVariable)”.

Well, it didn’t turn out to be that easy (at least not that I found), but it did turn out to be relatively simple. Eliding the part about actually finding the variables, I was able to accomplish what I wanted with this method:

/// Convert the local variable declaration to FSG's standard of explicit typing
/// Variable object to convert
/// A string with the new type declaration
public string ConvertDeclaration(Variable variable)
{
    var myImplicit = variable as ImplicitVariable;
    string myString = variable.MemberType;
    if (myImplicit != null)
    {
        var myObjectCreation = myImplicit.Expression as ObjectCreationExpression;
        if (myObjectCreation != null && myObjectCreation.ObjectType != null)
        {
            myString = myObjectCreation.ObjectType.ToString();
        }

        var myArrayCreate = myImplicit.Expression as ArrayCreateExpression;
        if (myArrayCreate != null)
        {
            myString = myArrayCreate.BaseType.ToString();
        }
    }
    return myString;
}

This isn’t actully my finished ‘production’ code, but it’s easier to display in this format. I didn’t like the size of that method, so I created an abstract ExplicitExpressionConverter and gave it inheritors ObjectCreationExpressionConverter and ArrayCreateExpressionConverter, using a factory method creation pattern to figure out which to create, based on the variable. But while that abstraction makes the code cleaner, it makes the logic harder to document in a blog post.

So, anyway, the idea here is that you need to convert the variable you find into the appropriate type of expression. An object creation expression is standard allocation, and the array create expression is a special case. There are other special cases as well, such as null coalescing (var myFoo = someClass.GetAFoo() ?? new Foo()) and method call expression (var myFoo = someClass.GetAFoo()), but I have not yet figured out how to obtain the return type from those expressions. I’ll probably add a part 4 if/when I do.

By

Getting Started With Moles

Microsoft Moles seems pretty cool, so I’ve decided to set it up and play with it. However, because it’s a research project, the documentation isn’t exactly thorough. I found some videos and various tutorials but nevertheless had a lot of digging in order to get it working. I’m going to document some of the hurdles here for posterity and for myself, in case I need to do this again.

Installation

First off, I’ve been using Pex for a while now, so I just assumed that I’d have Moles installed. It appeared as though this wasn’t the case when I watched a Moles startup video. You see, I didn’t have the template that he references in the video, and I got no joy from doing “devenv /installvstemplates” (which, by the way, is very handy if you find that you’re missing some template that should be installed for whatever reason). As it turns out, the reason I don’t have it is because it’s apparently now deprecated and not the way things are done. I didn’t find this out until after I had un-installed and re-installed Pex and Moles, so I don’t know whether or not Moles was originally functioning with Pex. Probably, but who knows?

Getting Started

After that, I browsed a few posts like this one and saw that the thing I should be going for is getting these M types up and recognized by Intellisense. For instance, I want to test a class that’s using the System.IO.Directory class, so what I want is “MDirectory” for creating Moles. I got the sense that the thing to do here was to right-click on the library reference in question (i.e. “System”) and add a Moles assembly. This is wrong. Very wrong. I got about 25 compiler errors after I tried to build.

By trial and error (read: luck), I discovered that you want to right-click on “References” in your test project and “Add Moles Assembly For mscorlib.”

Adding Moles for mscorlib

Type was not instrumented…huh?

Once I’d gotten my M types in place, I was set to go. So I coded up a test that should pass if I implemented the delegate logic correctly, and I ran it. At this time, I got an exception in the test run. In opening the test result details, the Moles team was actually helpful enough to include this comment in the results:

“To resolve this issue, add the following attribute in the test project:

using Microsoft.Moles.Framework;
[assembly: MoledType(typeof(System.IO.Directory))]”

That’s pretty helpful. So, okie-dokie…and, viola! It passed.

Actual Use

If you understand functions and delegates, there’s not a lot to actual use. Once I’d gotten the annoyances out of the way, using this was actually very easy, and I found it to be quite powerful.

One thing I noticed is that it does introduce a bit of overhead when you start your test run. I’m keeping my eye on this to see if it’s a one-time, up-front cost, or if it scales and causes your test runs to be slower as you use it more.

Moling your own classes

This was fairly straightforward if you’re moling your public classes. You just right-click on your project under test in the test project’s references and select “Add Moles Assembly.” It gets a little more interesting if you want to mole internal classes.

To do this, open up the AssemblyInfo.cs class of your project under test and add an [assembly: InternalsVisibleTo(“{YourProjectNamespace}.Moles”)]. In order to know exactly what to add, just mimic the new reference that appears in your test project after you add a new moles assembly.

Moling constructors

For most instance based methods, the declaration looks something like:

MStreamReader.AllInstances.ReadToEnd = (o) => { return @"C:\ and some other stuff"; };

That is, you’ll get pretty used to the “AllInstances,” it appears. But one gotcha is that you mole a constructor like this:

MStreamReader.ConstructorString = (sr, s) => { };

That’s not really that big of a gotcha, but I’m just kind of documenting here all the things that I had to go poking around to figure out.

By

Directory Browser Dialog

One of the things that’s always surprised me about WPF is the lack of any kind of out-of-the-box file/directory browser dialog. It seems as though every time this comes up, I poke around the internet, hoping that it’s been added in some kind of update somewhere, but it never is. At least, it never is in the scope and skill of my google skills, anyway.

So, I wrote one for WPF. There’s nothing particularly hard about this, and I don’t view it as some kind of breakthrough. The reason that I’m making this post is that I noticed a trend that I find rather irritating. Whenever I’m searching for something like this, I seem to encounter two kinds of posts: posts that offer some zipped Visual Studio project I can download and plugin or else some vague, incomplete suggestion of what to do.

As for me personally, I’m just looking for functional code that I can slam right into my project. I don’t really want to download things and I don’t really want to spend the effort coding up something that I think should already exist. That is to say, I have no issue getting my hands dirty when I can learn something or customize, but I’m also not a big proponent of reinventing the wheel.

I’m posting here to break this trend that I noticed. This is a completely functional solution that exists not at all beyond what you see here. I’m hoping this appeals to people with tastes like mine. I like to see all the code but without downloading things.

So, without further ado:


    
        
    

Above is the XAML for the user control and below is the code behind

public partial class DirectoryDialog : UserControl
{

    /// This is to allow for binding of the directory path obtained by this control
    public static readonly DependencyProperty DirectoryPathProperty = DependencyProperty.Register("DirectoryPath", typeof(string), typeof(DirectoryDialog),
        new FrameworkPropertyMetadata((string)string.Empty, FrameworkPropertyMetadataOptions.AffectsRender));

    public string DirectoryPath { get { return (string)GetValue(DirectoryPathProperty) ?? string.Empty; } set { SetValue(DirectoryPathProperty, value); } }


    /// Initializes the directroy dialog user control and sets data context to self
    public DirectoryDialog()
    {
        InitializeComponent();
    }

    /// Handler for when user double clicks the file box
    /// I try to avoid code behind whenever possible.  Logic in declarative markup sucks for debugging and testing,
    /// and code behind is inherently hard to debug and test, but this is an exception.  I don't want this COM construct
    /// anywhere near something I'm planning to unit test. =) 
    private void HandleDoubleClick(object sender, MouseButtonEventArgs e)
    {
        using (var myDialog = new System.Windows.Forms.FolderBrowserDialog())
        {
            if (!string.IsNullOrEmpty(DirectoryPath))
            {
                myDialog.SelectedPath = DirectoryPath;
            }
            myDialog.ShowDialog();
            DirectoryPath = myDialog.SelectedPath;
        }
    }
}

An example user of this is here:


        
            
            
        

As you can see, this is about as simple as it gets. If I have use for it, I’ll probably later rename the control to something like ChooserDialog and allow it to have modes of “File” and “Directory” which pop up their respective kinds of dialogs. This could certainly be extended and made snazzier, and maybe I’ll do that with time. And, maybe when I do, I’ll post a link allowing people to download it, but I will also post the code so that you can inspect it without jumping through hoops, and you can see if it suits your needs.