Click here to Skip to main content
6,630,289 members and growing! (23,129 online)
Email Password   helpLost your password?
License: The Code Project Open License (CPOL)

How To Bind To Generic Method In XAML

By Sacha Barber

As some of you that have worked with XAML and Generics may know, there is currently no support for Generics in XAML (that is no support for direct binding of methods that use generics).So consider this problemThat I have various bits of static data that are used through out the system, that are he
All Topics
Version:2 (See All)
Posted:17 Jun 2009
Views:1,760
Bookmarked:4 times
Technical Blog
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
0 votes for this technical blog
A Technical Blog article. View entire blog here.

As some of you that have worked with XAML and Generics may know, there is currently no support for Generics in XAML (that is no support for direct binding of methods that use generics).

So consider this problem

That I have various bits of static data that are used through out the system, that are held as a collection(s) (I am using ObservableCollection<t>) of certain data objects. The WPF UI should be able to bind to these collections, without the need for loads of get {…} properties. Ideally there would be a single method that returned the correct type of static data, as requested by the method. I mean there may be a lot of static data, and sure we could do this by exposing lots of properties over the static data collections, but that somehow seems old fashioned to me. We could of course also just take an Object and return a ObservableCollection, but that to seemed wrong, not enough typing more my liking there. The problem seems to warrant a more generic solution. Wait, doesn’t .NET support generics. Hell yeah, ok cool. So possibly we should be trying for something like the following after all:

   1:  public ObservableCollection<T> GetForType<T>()
   2:  {
   3:      return (ObservableCollection<T>)
              typeToCollectionLookup[typeof(T)];
   4:  }

This seems to fit the problem domain, but how could we do this in XAML.

Unfortunately I do not know a way of dealing with generic method calls in XAML. I know there is a ObjectDataProvider object which has a Method property and allows parameters to be built up in XAML. But this would mean we would need one new ObjectDataProvider with parameters for each type we intended to use the above method for. That’s pretty poor. There must be a better way, surely.

Shown below is an attached property that could be used with a ComboBox control to bind to which will populate the ComboBox.ItemsSource property by calling the generic method.

So all you have to do in the XAML is

   1:  <Window x:Class=”GenericBinding.Window1″
   2:      xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
   3:      xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
   4:      xmlns:local=”clr-namespace:GenericBinding;assembly=”
   5:      Title=”Window1″ Height=”300″ Width=”300″>
   6:      <Grid>
   7:  
   8:  
   9:          <ComboBox
  10:         local:ComboBoxProps.BoundCollectionType=”local:Person”/>
  11:  
  12:  
  13:      </Grid>
  14:  </Window>

Where the ComboBoxProps.BoundCollectionTypeProperty attached property is declared liked this

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using System.Windows;
   6:  using System.Windows.Controls;
   7:  using System.Reflection;
   8:  using System.Collections;
   9:  
  10:  namespace GenericBinding
  11:  {
  12:      /// <summary>
  13:      /// Provides a mechanism for binding a ComboBox.ItemSource against
  14:      /// a generic method within the StaticData singleton. Where the generic
  15:      /// method has a signature as follows:
  16:      /// 
  17:      /// public ObservableCollection<T> GetForType<T>()
  18:      /// </summary>
  19:      public class ComboBoxProps
  20:      {
  21:          #region BoundCollectionType
  22:  
  23:          /// <summary>
  24:          /// BoundCollectionType Attached Dependency Property
  25:          /// </summary>
  26:          public static readonly DependencyProperty
                   BoundCollectionTypeProperty =
  27:              DependencyProperty.RegisterAttached(
                   “BoundCollectionType”,
  28:              typeof(Type), typeof(ComboBoxProps),
  29:                  new FrameworkPropertyMetadata(null,
  30:                      new PropertyChangedCallback(
                            OnBoundCollectionTypeChanged)));
  31:  
  32:          /// <summary>
  33:          /// Gets the BoundCollectionType property.  
  34:          /// </summary>
  35:          public static Type GetBoundCollectionType
                     (DependencyObject d)
  36:          {
  37:              return (Type)d.GetValue(
                       BoundCollectionTypeProperty);
  38:          }
  39:  
  40:          /// <summary>
  41:          /// Sets the BoundCollectionType property.  
  42:          /// </summary>
  43:          public static void SetBoundCollectionType(
                     DependencyObject d, Type value)
  44:          {
  45:              d.SetValue(BoundCollectionTypeProperty, value);
  46:          }
  47:  
  48:          /// <summary>
  49:          /// Handles changes to the BoundCollectionType property.
  50:          /// Uses Reflection to obtain the method within the StaticData singleton class
  51:          /// that has the generic method that we need to use to get the values from.
  52:          /// The method will be marked with a custom ItemsSourceLookUpMethodAttribute
  53:          /// to indicate which method is to be used, to create a Dynamic call to
  54:          /// using the correct generic parameter.
  55:          /// </summary>
  56:          private static void OnBoundCollectionTypeChanged(DependencyObject d,
  57:              DependencyPropertyChangedEventArgs e)
  58:          {
  59:              ComboBox cbSource = d as ComboBox;
  60:              Type t = (Type)e.NewValue;
  61:              Type[] types = new Type[] { t };
  62:  
  63:              MethodInfo[] methods =
  64:                  typeof(StaticData).GetMethods(BindingFlags.Public |
                       BindingFlags.Instance);
  65:  
  66:              foreach (MethodInfo method in methods)
  67:              {
  68:                  //Didnt like looking up MethodInfo.Name based on a string as it could
  69:                  //change, so use a custom attribute to look for on the method instead
  70:  
  71:                  ItemsSourceLookUpMethodAttribute[] attribs =
  72:                      (ItemsSourceLookUpMethodAttribute[])
  73:                          method.GetCustomAttributes(
  74:                              typeof(ItemsSourceLookUpMethodAttribute), true);
  75:  
  76:                  //is this the correct MethodInfo to invoke
  77:                  if (attribs.Length > 0)
  78:                  {
  79:                      // create the generic method
  80:                      MethodInfo genericMethod = method.MakeGenericMethod(types);
  81:                      cbSource.ItemsSource =
  82:                          (IEnumerable)genericMethod.Invoke(StaticData.Instance,
  83:                          BindingFlags.Instance, null, null, null);
  84:                  }
  85:              }
  86:          }
  87:          #endregion
  88:      }
  89:  }

If you want to see a full example you can read more about this on the codeproject article link shown below

http://www.codeproject.com/KB/WPF/GenericXAML.aspx

Hope this helps you as much as it did me. Enjoy

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sacha Barber


Member
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Occupation: Software Developer (Senior)
Location: United Kingdom United Kingdom

Other popular Uncategorised Technical Blogs articles:

  • Multi-Threading in ASP.NET
    ASP.Net Threading Inside the ASP.Net Worker Process there are two thread pools. Theworker thread pool handles all incoming requests and the I/O Threadpool handles the I/O (accessing the file system, web services anddatabases, etc.). Each App Domain has its own thread pool and thenumber of ope
  • Delegates Explained in Plain English
    CodeProjectDelegates are fundamental to the .NET Framework (events and callbacks wouldn't work without them) and can be extremely powerful to the .NET Developer once they come to grasps with exactly what they are and how to use them. In this blog I will consider aspects of a real world situation in
  • Windows 7 Tricks and Keyboard Shortcuts
    I’ve been running Windows 7 RC for a little over a week now and can’t imagine going back to Vista at this point. I decided to start with a fresh install of Windows 7, so I’ve been in the process of reinstalling all of my applications and cleaning up my disk drives. In the process, I went searching
  • iPhone Gaming Framework: Stage 1 Tutorial
    The goal for this tutorial is to get a basic screen management system up and running, ready to start writing game code.
  • Thread Safe Generic Queue Class
    I've been doing a lot of mult-threading work, recently, using the standard Thead class, the Worker Queue, and the new PLINQ (Parallel LINQ). The problem with most of the built-in generic collections (Queue, List, Dictionary, etc), is that they are not thread safe.I created a library of
Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
  (Refresh) 
-- There are no messages in this forum --

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Jun 2009
Editor: Sean Ewington
Copyright 2009 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project