DevExpress’ FlowLayoutControl and MVVM

by Miha Markič 30. August 2011 11:45

FlowLayoutControl unfortunately doesn’t support items binding. You can’t just provide a source and hope FlowLayoutControl will populate the content. But fear not, there is nothing attached properties can’t solve.

I’ve created an attached property ItemsSource that does all that for you. Here is its declaration:

public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.RegisterAttached("ItemsSource", typeof(IEnumerable), typeof(FlowLayoutExtensions), 
            new UIPropertyMetadata(null, new PropertyChangedCallback(OnItemsSourceChanged)));

It accepts an IEnumerable as an input.

And here is the relevant code when ItemsSource changes:

private static void OnItemsSourceChanged(DependencyObject o, IEnumerable oldValue, IEnumerable newValue)
{    
    FlowLayoutControl layout = o as FlowLayoutControl;
    if (layout != null)
    {

        NotifyCollectionChangedEventHandler collectionChanged = delegate(object s, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    AddItems(layout, e.NewItems);
                    break;
                case NotifyCollectionChangedAction.Remove:
                    RemoveItems(layout, e.OldItems);
                    break;
            }
        };

        // remove event implementation
        if (oldValue != null)
        {
            INotifyCollectionChanged oldIncc = oldValue as INotifyCollectionChanged;
            if (oldIncc != null)
                oldIncc.CollectionChanged -= collectionChanged;
        }
        layout.Children.Clear();

        if (newValue != null)
        {
            AddItems(layout, newValue);
            INotifyCollectionChanged incc = newValue as INotifyCollectionChanged;
            if (incc != null)
            {
                incc.CollectionChanged += collectionChanged;
            }
        }
    }
}

First it defines a delegate that gets called upon collection changes (when source is INotifyCollectionChanged) then it unsubscribes from CollectionChanged if it has previously subscribed. And finally it populates FlowLayoutControl with items and optionally subscribes to CollectionChanged event (when source supports it). Note that ObservableCollection<T> implements INotifyCollectionChanged.

Here is the code that adds or removes items:

private static void AddItems(FlowLayoutControl layout, IEnumerable source)
{
    foreach (object item in source)
    {
        GroupBox box = new GroupBox { DataContext = item };
        layout.Children.Add(box);
    }
}

private static void RemoveItems(FlowLayoutControl layout, IEnumerable source)
{
    foreach (object item in source)
    {
        GroupBox match = (from gb in layout.Children.OfType<GroupBox>()
                          where gb.DataContext == item
                          select gb).FirstOrDefault();
        if (match != null)
            layout.Children.Remove(match);
    }
}

Add items adds an GroupBox instance for each new item and sets its DataContext to the item. While RemoveItems searches for a matching GroupBox (based on DataContext match) instance and removes it from the FlowLayoutControl's Children collection.

A bit of XAML is required as well. I control the GroupBox appearance through a Style, like this:

<Style TargetType="dxlc:GroupBox">
    <Setter Property="MaximizeElementVisibility" Value="Visible"/>
    <Setter Property="MinimizeElementVisibility" Value="Visible"/>
    <Setter Property="Width" Value="150"/>
    <Setter Property="Header" Value="{Binding Caption}" />
    <Setter Property="Content" Value="{Binding}" />
</Style>

Note the binding of the Content property (remember, I am assigning current item as DataContext). And here is the FlowLayoutControl instance declaration:

<dxlc:FlowLayoutControl loc:FlowLayoutExtensions.ItemsSource="{Binding}" />

There you go, a MVVM friendly approach.

Note that this is not a fully featured code but it is a good starting point.

31.8.2011 - correct demo files

20.9.2011 - ufff, again uploaded really proper demo

FlowLayoutExtensionsDemo.zip (9.99 kb)

Tags: , ,

.net | DevExpress

Comments (8) -

dmitry
dmitry Russia
8/31/2011 5:40:49 PM #

Cool. This is what I am looking for! Smile

Reply

Miha Markic
Miha Markic Slovenia
8/31/2011 5:54:05 PM #

Hi Dmitry,

Thanks for the feedback (that demo files are wrong). It should be proper ones now.

Reply

Marko
Marko Slovenia
9/20/2011 11:29:54 AM #

The demo file is still wrong.
It contains no usefull code at all. There is just App and MainWindow (both of them empty) in the project. And there's no flow layout extensions present.

Reply

Miha Markic
Miha Markic Slovenia
9/20/2011 11:50:16 AM #

aaaaarggghhh, this demo is doomed. I swear I really uploaded the correct demo this time. Thanks for the feedback.

Reply

dmitry
dmitry Russia
8/31/2011 8:56:17 PM #

Yes, I tried to say you that, but there were something wrong with capcha

Reply

Pierre Lamontagne
Pierre Lamontagne Canada
12/1/2011 6:17:36 PM #

Truly appreciate this example.
This extension is now part of my tool bag.
Good work.

Reply

Mark
Mark United Kingdom
12/2/2011 4:54:45 PM #

There's a bug in your code - the un-subscription from the CollectionChanged event will never work, because a new delegate is created each time the static function is called.

Reply

Miha Markic
Miha Markic Slovenia
12/3/2011 12:53:46 PM #

Hi Mark,

That's a good point. However, the code should work nevertheless unless I am mistaken Smile.
The compiler creates an anonymous method (delegate implementation) and each time a delegate is created it points to that method. Thus they are treated as equal and correctly removed when required. Perhaps the notation is misleading.

Reply

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Miha Markic

About me
Righthand
 
Microsoft MVP
 
Developer Express' DXSquad
INETA Country Leader for Slovenia
INETA Country Leader for Slovenia

Slovene Developer Users Group Lead
Friends of Red-Gate
LLBLGenPro Partner

Miha currently works as a free lance consultant and software developer specialized in .net area.
He graduated in Computer and information science at the University of Ljubljana, Slovenia. He has accumulated experience in various programming languages such as Java, Visual Basic 3-6 (MCP), Visual C++, Delphi, C# and VB.Net through years.
He has experience in practically all (technical) stages of project development, including planning, framework development, user interface, business processes, as well as testing and documenting. He has worked on big and small projects in Slovenia and abroad (e.g. participated in completing level 3 IS for the Nucor steel plant, Hertford, USA).
Currently he enjoys programming in .net environment using C#. Since 2000 he has been active in Developer Express' DX Squad and has been ECDL trainer and tester. He also gives lectures on conferences and other events in Slovenia.

Month List

Tag cloud

Most comments

Dan Dan
4 comments
ca Canada
Thomas Thomas
3 comments
de Germany
Sebastian Sebastian
1 comments
ca Canada

RecentComments

Comment RSS