none
LightSwitch TreeView Custom Control

    Question

  • I'm building a quick app but I need to use a tree view. I created the custom control and it seems to be working but the issue I have is that it seems that LS is loading only the main nodes and it will not load the childs until one item is selected.

    Bottom line, if I use the control in SL with RIA and EDM it works (I do the Include childs on the return IQueryable) but in LS it only gets the Nodes (no childs).

    Is there a solution for that?

    Thanks and keep the great work!!!!

    Massimo

    Monday, November 01, 2010 11:47 PM

Answers

  •  

    Massimo,

     

    sorry for very late reply. From our private conversation I learned you have a table with a self-referencing relationship and you want to display the content of this table in a TreeView control. Let's say the table you use has the following structure:

     

    Locations

    Id int primary key

    Name nvarchar(128) not null

    Parent int null

     

    When you create the relationship in LightSwitch, the designer will also create a navigation property for the child records. I called it ChildLocations.

     

    {

    Here is what the data might look like:

     

    Id   Name                Parent

    ---------------------------------

    1    Pacific Northwest

    2    California

    3    Southwest

    4    The Rockies

    5    Washington          1

    6    Oregon              1

    7    Arizona             3

    8    Nevada              3

    9    New Mexico          3

    10   Idaho               4

    11   Colorado            4

    12   Montana             4

    }

     

    To show all Locations as a tree inside LightSwitch application you'd create a screen with a collection property to hold all Locations and then drag and drop this property to the screen content tree. Then, for the newly created content item you would change the control to custom control (your TreeView). The way to set up the control is very similar to what you would do with a vanilla SL/RIA application, but there is one important exception that is related to LightSwitch threaading model. Without going into the details, the basic limitation is that you cannot enumerate the children from the UI thread; you have to do it from the screen logical thread. To overcome this I have created a ValueConverter that will do necessary cross-thread dance. Here is the code:

     

        // Ensures that an entity collection is loaded before accessed by UI thread.

        // The binding should use the whole entity object as data binding context

        public class EntityCollectionValueConverter : IValueConverter

        {

     

            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

            {

                IEntityObject entity = value as IEntityObject;

                if (entity == null) throw new ArgumentException("The converter should be using an entity object");

     

                string sourcePropertyName = parameter as string;

                if (string.IsNullOrWhiteSpace(sourcePropertyName)) throw new ArgumentException("Converter parameter should be set to the property name that will serve as source of data");

     

                // Enumerate the source property using logic dispatcher

                // and prepare the collection of entities that the control will bind to

                var entities = new ObservableCollection<IEntityObject>();

                var temporaryEntites = new List<IEntityObject>();

     

                entity.Details.Dispatcher.BeginInvoke(delegate

                {

                    IEntityCollection eCollection = entity.Details.Properties[sourcePropertyName].Value as IEntityCollection;

                    if (eCollection == null)

                    {

                        Debug.Assert(false, "The property " + sourcePropertyName + " is not an entity collection");

                        return;

                    }

     

                    // Now we are on the logic thread. We cannot just stuff the observable collection

                    // with entities because the collection will immediately raise Changed events

                    // and this will result in invalid cross-thread access. So we'll use a temporary collection

                    // and copy the entites again on the UI thread

                    foreach (IEntityObject e in eCollection)

                    {

                        temporaryEntites.Add(e);

                    }

     

                    Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(delegate

                    {

                        // I wish ObservableCollection had an AddRange() method...

                        foreach (IEntityObject e in temporaryEntites)

                        {

                            entities.Add(e);

                        }                   

                    });

                   

                });

     

                return entities;

            }

     

            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

            {

                throw new NotImplementedException();

            }

        }

     

     

    I am using this converter to setu up a HierarchicalDataTemplate inside my TreeView control like this:

     

    <UserControl x:Class="MassimoControls.LocationsTreeView"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"

        xmlns:winControls="clr-namespace:System.Windows;assembly=System.Windows.Controls"        

        xmlns:local="clr-namespace:MassimoControls"

        mc:Ignorable="d"

        d:DesignHeight="300" d:DesignWidth="400">

       

        <UserControl.Resources>

            <local:EntityCollectionValueConverter x:Key="EntityCollectionValueConverter" />

        </UserControl.Resources>

       

        <Grid x:Name="LayoutRoot" Background="White">

            <StackPanel Orientation="Horizontal">

                <controls:TreeView Name="treeViewControl" ItemsSource="{Binding Value}">

                    <controls:TreeView.ItemTemplate>

                        <winControls:HierarchicalDataTemplate ItemsSource="{Binding Converter={StaticResource EntityCollectionValueConverter}, ConverterParameter=ChildLocations}">

                            <StackPanel Orientation="Horizontal">

                                <TextBlock Text="{Binding Path=Name, Mode=OneWay}" Margin="5,0" />

                            </StackPanel>

                        </winControls:HierarchicalDataTemplate>

                    </controls:TreeView.ItemTemplate>

                </controls:TreeView>

            </StackPanel>

     

        </Grid>

    </UserControl>

     

    This is just a sample, but hopefully will point you in the right direction. Let me know how it goes!

     

    Cheers, Karol

     

    Friday, December 10, 2010 1:03 AM
  • Thanks again for this excellent example. However, I have a problem with the databinding. Every item is displayed correctly in the hierarchy, and then every item is displayed as if it was root, as shown below.

    Root

    ---sub1

    ------sub11

    ---sub2

    ------sub21

    sub1

    sub11

    sub2

    sub21

     

    Any idea what can be wrong. It seems to me that I copied-pasted the code.

    Thanks.

    René

     


    Whats happening is that the Tree is binding to all the nodes. You actually want the Tree to bind only to the "root nodes" (nodes that do not have a parent). The child nodes (of the root nodes) will then be displayed as the Tree control recursively walks the collection.

    I added a bool property to my collection call "IsRootNode". I then created a query that only returned root nodes. this is the query that I bound to the Tree Control.

    code sample: Tree Control: Hierarchical Data with LightSwitch

     


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com


    Sunday, August 21, 2011 8:54 PM

All replies

  •  

    Massimo,

     

    sorry for very late reply. From our private conversation I learned you have a table with a self-referencing relationship and you want to display the content of this table in a TreeView control. Let's say the table you use has the following structure:

     

    Locations

    Id int primary key

    Name nvarchar(128) not null

    Parent int null

     

    When you create the relationship in LightSwitch, the designer will also create a navigation property for the child records. I called it ChildLocations.

     

    {

    Here is what the data might look like:

     

    Id   Name                Parent

    ---------------------------------

    1    Pacific Northwest

    2    California

    3    Southwest

    4    The Rockies

    5    Washington          1

    6    Oregon              1

    7    Arizona             3

    8    Nevada              3

    9    New Mexico          3

    10   Idaho               4

    11   Colorado            4

    12   Montana             4

    }

     

    To show all Locations as a tree inside LightSwitch application you'd create a screen with a collection property to hold all Locations and then drag and drop this property to the screen content tree. Then, for the newly created content item you would change the control to custom control (your TreeView). The way to set up the control is very similar to what you would do with a vanilla SL/RIA application, but there is one important exception that is related to LightSwitch threaading model. Without going into the details, the basic limitation is that you cannot enumerate the children from the UI thread; you have to do it from the screen logical thread. To overcome this I have created a ValueConverter that will do necessary cross-thread dance. Here is the code:

     

        // Ensures that an entity collection is loaded before accessed by UI thread.

        // The binding should use the whole entity object as data binding context

        public class EntityCollectionValueConverter : IValueConverter

        {

     

            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

            {

                IEntityObject entity = value as IEntityObject;

                if (entity == null) throw new ArgumentException("The converter should be using an entity object");

     

                string sourcePropertyName = parameter as string;

                if (string.IsNullOrWhiteSpace(sourcePropertyName)) throw new ArgumentException("Converter parameter should be set to the property name that will serve as source of data");

     

                // Enumerate the source property using logic dispatcher

                // and prepare the collection of entities that the control will bind to

                var entities = new ObservableCollection<IEntityObject>();

                var temporaryEntites = new List<IEntityObject>();

     

                entity.Details.Dispatcher.BeginInvoke(delegate

                {

                    IEntityCollection eCollection = entity.Details.Properties[sourcePropertyName].Value as IEntityCollection;

                    if (eCollection == null)

                    {

                        Debug.Assert(false, "The property " + sourcePropertyName + " is not an entity collection");

                        return;

                    }

     

                    // Now we are on the logic thread. We cannot just stuff the observable collection

                    // with entities because the collection will immediately raise Changed events

                    // and this will result in invalid cross-thread access. So we'll use a temporary collection

                    // and copy the entites again on the UI thread

                    foreach (IEntityObject e in eCollection)

                    {

                        temporaryEntites.Add(e);

                    }

     

                    Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(delegate

                    {

                        // I wish ObservableCollection had an AddRange() method...

                        foreach (IEntityObject e in temporaryEntites)

                        {

                            entities.Add(e);

                        }                   

                    });

                   

                });

     

                return entities;

            }

     

            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

            {

                throw new NotImplementedException();

            }

        }

     

     

    I am using this converter to setu up a HierarchicalDataTemplate inside my TreeView control like this:

     

    <UserControl x:Class="MassimoControls.LocationsTreeView"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"

        xmlns:winControls="clr-namespace:System.Windows;assembly=System.Windows.Controls"        

        xmlns:local="clr-namespace:MassimoControls"

        mc:Ignorable="d"

        d:DesignHeight="300" d:DesignWidth="400">

       

        <UserControl.Resources>

            <local:EntityCollectionValueConverter x:Key="EntityCollectionValueConverter" />

        </UserControl.Resources>

       

        <Grid x:Name="LayoutRoot" Background="White">

            <StackPanel Orientation="Horizontal">

                <controls:TreeView Name="treeViewControl" ItemsSource="{Binding Value}">

                    <controls:TreeView.ItemTemplate>

                        <winControls:HierarchicalDataTemplate ItemsSource="{Binding Converter={StaticResource EntityCollectionValueConverter}, ConverterParameter=ChildLocations}">

                            <StackPanel Orientation="Horizontal">

                                <TextBlock Text="{Binding Path=Name, Mode=OneWay}" Margin="5,0" />

                            </StackPanel>

                        </winControls:HierarchicalDataTemplate>

                    </controls:TreeView.ItemTemplate>

                </controls:TreeView>

            </StackPanel>

     

        </Grid>

    </UserControl>

     

    This is just a sample, but hopefully will point you in the right direction. Let me know how it goes!

     

    Cheers, Karol

     

    Friday, December 10, 2010 1:03 AM
  • Hi Massimo,

    I have exactly the same problem. Currently I'm trying to create a TreeViewControl Extension but
    I'm not getting how the data is going to be bound to the control and what properties and datatemplates I have to provide.

    Is it possible for you to give me the source for your treeviewcontrol?

    my mail adress: eugen.berenstein@googlemail.com

     

    thx for the answer in advance.

     

    Wednesday, December 15, 2010 2:56 PM
  • Hi,

    I'm also trying to insert a TreeView as user control in my lightswitch application.

    Karol's converter seems to be the solution of my problem. But there are things I don't understand...

    I created a SilverLight Class Library and then a SilverLight User Control. I added my TreeView into .xaml file.
    I added a class implementing IValueConverter.

    My problem:
    I cannot resolve the "IEntityObject" interface, it seems to be located in Microsoft.Lightswitch.dll that I can not import as 

    reference in my SilverLight project.

    Do you have any solutions?

    Thanks
    Tuesday, January 18, 2011 10:22 AM
  • Hmm, can you describe in more detail why you cannot add a reference to Microsoft.LightSwitch.dll to your project?

    I checked my project and I am referencing Microsoft.LightSwitch, Microsoft.LightSwitch.Client and Microsoft.LightSwitch.Base.Client from the project that has the converter implementation. As far as I remember I did not run into any difficulties when adding a reference to these assemblies. They are all located under (VS installation directory)\Common7\IDE\LightSwitch\1.0\Client.

    Hope that helps, Karol

    Tuesday, January 18, 2011 4:41 PM
  • Karol, thanks for your answer.
    Effectivly, I tried with the wrong file...
    Wednesday, January 19, 2011 2:39 PM
  • Thanks Karol, for this excellent example of self referencing LightSwitch treeview! This is exactly what I was looking for.

    However, I need to take it one step further and would like your advice as I have been running into walls that I don’t understand. I want to enable drag and drop treeview in LightSwitch.

    I have built your example within LightSwitch and separately have built my own Silverlight Navigation project utilizing RIA Services (connected to LightSwitch Table) converted to an ObservableCollection to track/save changes within a SilverLight treeview and a button to save the changes. Both work perfectly as standalone, yours as a view/new/edit and mine as rearrange children under parent.

    I am fairly new at SilverLight, LightSwitch and RIA Services. My questions to you are how would you proceed based on your knowledge/experience?

    1.       I think that the easiest way would be to have a button close to your LightSwitch treeview to “Arrange Parent”. Then from that call my other SilverLight project utilizing RIA/ObservableCollection/DragDrop based on a filtering string passed from LightSwitch to a modal window when the button is pressed.

    2.       Can the two implementations be joined together? And if so, how would you go about doing that? In your SilverLight treeview example, how can I take that to an ObservableCollection to bind to the treeview for Drag Drop and then save changes to the DB?

    3.       If I need to go with item 1, can the LightSwitch application understand the .web part of my project based on MVVM? Can I just add both the Silverlight and the Web project to the solution and LightSwitch let it all pass through like it was standalone?

    Thanks!

    Matt

    Saturday, May 28, 2011 12:51 AM
  • Thanks again for this excellent example. However, I have a problem with the databinding. Every item is displayed correctly in the hierarchy, and then every item is displayed as if it was root, as shown below.

    Root

    ---sub1

    ------sub11

    ---sub2

    ------sub21

    sub1

    sub11

    sub2

    sub21

     

    Any idea what can be wrong. It seems to me that I copied-pasted the code.

    Thanks.

    René

     

    Wednesday, June 15, 2011 6:40 PM
  • Hi Rene,

    I had the same issue at first with just displaying the treeview. In my case, an item was part of the root because it was associated to another table. Think a Contract has a number of BOM’s in the root in which the BOM’s have children. I added the contract table relationship to my BOM table. I populated a few contracts in the contracts table. In the BOM table, I associated a few contracts to the top level BOM items that I wanted to be in the root. I was able to make another form based on contracts along with the BOM table as second data source. I converted the BOM data source to the custom Silverlight control just as before per instructions. Then it only displayed root BOM nodes that were assigned to the selected contract. All of the sub nodes displayed as normal. For me this was what I wanted, all but I can’t make the drag and drop work.

     

    Thanks,

    Matt

    Wednesday, June 15, 2011 11:43 PM
  • I have arrange your code in order to do a custom screen with CRUD+Cut&Paste Operations.

    I have a problem with casting. I can't replace:

    Dim x As Microsoft.LightSwitch.Framework.Client.VisualCollection(Of LightSwitchApplication.dimActivitat ) = TryCast(Screen.Details.Properties(strQueryName).Value, Microsoft.LightSwitch.Framework.Client.VisualCollection(Of LightSwitchApplication.dimActivitat))

    x.SelectedItem = ...

    With:

    Dim x As Microsoft.LightSwitch.Framework.Client.VisualCollection(Of IEntityObject ) = TryCast(Screen.Details.Properties(strQueryName).Value, Microsoft.LightSwitch.Framework.Client.VisualCollection(Of IEntityObject ))

    x.SelectedItem = ...

     

     Is ther a way to do this?

    Thursday, July 28, 2011 12:18 PM
  • Hey Matt, sorry for late reply. I haven't tried this scenario myself, but here is what I would try: there is an "experimental" TreeViewDragDropTarget class in Silverlight toolkit that takes care of most of the drag&drop machinery; you can wrap your TreeView control in it. The part that I am not sure about is what will be necessary to make it work with LightSwitch. Assuming that drag and drop operations result in Inserts and Removes from relevant collections, you will probably have to handle these collection operations yourself by doing the re-parenting of entity objects on the screen thread first and then modify collections that are used by the UI on the UI thread.

    Hope that helps--please post to the forum if you figure it out or if you have more questions!

    Karol

    Tuesday, August 02, 2011 11:52 PM
  • DaniHP, sorry, no, VisualCollection<T> is not covariant (the fancy name for ability to cast from Something<derived> to Something<base>) so you cannot do that. That said, we also have a weakly-typed VisualCollection type, so if you really do not care about specific entity types, I would try using that.

    Hope that helps!

    Karol

    Tuesday, August 02, 2011 11:55 PM
  • I have been working quite a number of hours trying to get this sample to work since I really need a treeview control in my LS app and this seems to be the first step in figuring out how to do that.

    What I am unsure about is exactly where the convert code that Karol presents above goes.  I put it in the Server\UserCode\ApplicationDataService.cs file and was finally able to resolve all the missing references.  Is this the right place to put it??

    Also I still have one error: the type 'local:EntityCollectionValueConverter' was not found.  This is in the XAML which is set up pretty much like Karol did it except I am using a SilverLight treeview control so the references to MassimoControls is different.

    So my questions are:  where is the right place to put the IValuieConverter class code and then how to I correct the EntityCollectionValueConverter reference in the XAML.  Maybe these are related?

    Thanks for any help anyone can shed on this.

    Saturday, August 20, 2011 11:57 PM
  • UPDATE:  I moved the converter code from Server\UserCode\ApplicationdataServices.cs to treeview.xaml.cs in the silverlightclass project.  I was able to again resolve all references including the one concerning entitycollectionvalueconverter that was vexing me so.

    However, the control still does NOT work.  No tree is displayed.  None of the entered sample data is displayed.  Just a blank box.  Very discouraging as I have been playing with this on and off for over two weeks now.

    Sunday, August 21, 2011 3:37 AM
  • I am still trying to figure out why this treeeview sample does not work for me.  I do notice that when I set breakpoints in the treeview code behind and the code fragment to initializecomponent that neither code is ever reached.  Why would this be?
    Sunday, August 21, 2011 4:50 PM
  • Thanks again for this excellent example. However, I have a problem with the databinding. Every item is displayed correctly in the hierarchy, and then every item is displayed as if it was root, as shown below.

    Root

    ---sub1

    ------sub11

    ---sub2

    ------sub21

    sub1

    sub11

    sub2

    sub21

     

    Any idea what can be wrong. It seems to me that I copied-pasted the code.

    Thanks.

    René

     


    Whats happening is that the Tree is binding to all the nodes. You actually want the Tree to bind only to the "root nodes" (nodes that do not have a parent). The child nodes (of the root nodes) will then be displayed as the Tree control recursively walks the collection.

    I added a bool property to my collection call "IsRootNode". I then created a query that only returned root nodes. this is the query that I bound to the Tree Control.

    code sample: Tree Control: Hierarchical Data with LightSwitch

     


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com


    Sunday, August 21, 2011 8:54 PM
  • Dear ElMiller,

    please make sure the and namespace of your control in the XAML file and the name and namespace of the code-behind file match. For example:

    namespace HtwControlLibrary
    {
        public partial class LocationsTreeView : UserControl
    <UserControl x:Class="HtwControlLibrary.LocationsTreeView"
    
    If they don't the control will not be initialized properly and data binding won't work. 
    Other things to remember: 
    	1. Make sure that the hierarchical relationship is defined for your entity, because this is what drives LightSwitch navigation property generation (Location.ChildLocations)
    	2. Make sure that properties of the Location entity (ChildLocations, Name) are spelled correctly inside TreeView hierarchical item template.
    	3. For debugging you might need to turn off Just My Code in Visual Studio debugging options
    Hope that helps! Let us know if you still can't figure it out.
    Karol 
    Sunday, August 21, 2011 10:45 PM
  • The namespace and the class names match with what is in the xaml.

    Location.ChildLocations relationship is setup and spelled correctly in the treeview hierarchy.

    Just My Code is now turned off.

    Still the control does not work and the breakpoints set in the treeview.xaml.cs are not triggered.  Also I tried to setup a simple SL checkbox in LS (same app) and that did not work either (and set breakpoints did not trigger).  Maybe I am doing something wrong in custom SL control setup?  I have gone thru several of the walkthrus in doing this and those always seemed to work.  If the bindings were not correct (getting bindings right seems hit and miss to me at this point) would the observed behaviour pertain in this case?  I mean, would there be some kind of error message or would the control just not work?  Would the breakpoints just not work?

    would it help to send screen shots or something?

    Thanks for you help, so far!

    Monday, August 22, 2011 2:04 AM
  • Progress at last!

     

    I was setting up my custom controls wrong.  In LS when I switched to a Custom Control it brought up a long list of controls from various sources.  Instead of looking under the controls for my specific SL control project I was selecting a control from the generic SL list.  With all these names being almost all alike I guess it was easy to overlook what I needed to do here.

    But now I have another problem.  It is late and I have not looked into it at all but here it is:  (Thanks again for your help and patience!!!)

    Monday, August 22, 2011 3:06 AM
  • This looks like an assertion from EntityCollectionValueConverter, around line 35 or so. Hit Cancel and see in the debugger what entity are you dealing with and why it does not have the expected property. Maybe it is just a bug in the sample and the assertion is unnecessary--let us know what you find!

     

    Monday, August 22, 2011 4:21 AM
  • Your tutorial is great, Michael. I followed it to the letter and was able to duplicate the tree! After a couple weeks of getting nowhere it is a real pleasure to finally succeed (albiet with plenty of help from you, Karol, and others). I bought your ebook on using SL controls in LS as soon as it came out several weeks ago and it has helped a great deal also (although with some of the issues I have had you can probably guess that some of its lessons did not fully sink in). Thanks also for the references to further reading and background. I will definite avail myself of that info.

    I do have one other question.  I'll be using the tree control with hierarchical data that is now in separate tables: e.g. country, state, county, city, etc. with the obvious relations.  Would you advise revising that so the data is in one self referencing table or revising the treeview infrastructure to work with the separate tables? 

    Many, many thanks again...

    Monday, August 22, 2011 3:03 PM
  • Ed, I probably wouldn't not change the data structure. This thread was focusing on a hierarchy involving instances of the same entity, but the technique should apply to hierarchy involving different types of entities as well. You just might need a different instance of HierarchicalDataTemplate for different levels in the hierarchy (separate template for Country, another one for State and so on), because the data you want to bind to/show for each level is obviously different.

    Knowing Michael he will probably produce a tutorial showing how to do this before I even press "Submit" button :-)

    Monday, August 22, 2011 4:06 PM
  • Your tutorial is great, Michael. I followed it to the letter and was able to duplicate the tree!

    Keep in mind that ALL the hard work was done by Karol. What I do is walk through the issue slowly and use a lot of screen shots with red arrows.

    Thank you for buying the book, but it could not have been written if Karol, Sheel, Michael Eng, and Joe Binder did not answer a ton of questions.

    There is a lot of technical information about LightSwitch out there because the LightSwitch team keeps "seeding the information flow".

    Alessandro Del Sole has a book coming out soon that got a lot of assistance from the LightSwitch team including Beth Massi. I actually sat in the same room with him as he and I were briefed by the LightSwitch team and they took our questions. At one point I had 3 LightSwitch team members huddled over my laptop helping to figure out how to deploy LightSwitch in a DotNetNuke website.

    My articles are really just a step in an "information flow" that starts with the LightSwitch team.

     

     


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com

    Monday, August 22, 2011 4:50 PM
  • Hi Karol,

     

    could you please elaborate how LS determines the type of the value parameter in the converter class? I for one have an example if I bind to a query using e.g. "Screen.Locations" that I cannot cast to IEntityObject (of course, as it is multiple objects). Furthermore, debugging yielded that I get a VisualCollection<Location> type. How would I handle that in order to convert a list of those instances properly?

    Thanks!!


    -- Holger Flick
    Monday, August 22, 2011 8:52 PM
  • With much help from Michael and Karol I was able to get the treeview control working with the self referencing table of sample data.  In my application my data is stored in separate tables: country, state, county, etc.  At first it looked pretty easy to convert the control, etc to work with this setup.  However I am now getting the error message below whenever the app is about to display data of a leaf node (not any of the root nodes).  I have messed around with the Xaml binding try to fix this but to no avail.  Anyone know what is causing this?  If i have two levels of hierarchy it always happens to the items at the second level (States).  If I have three levels of hierarchy it always happens to items at the 3rd level (county) but not the 2nd level.  (Not exactly always leaf nodes; more precisely at the lowest level being displayed).  If I chose to Ignore and continue it does so for each data item displayed at that level and then the error is never displayed again (unless I close/reopen the screen).  The Xaml for the treeview control is also below.  (Excuse my formatting of all this.)

    <UserControl x:Class="SilverlightProject.SilverlightTracsTreeControl"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:local="clr-namespace:SilverlightProject"  
      xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="500">
    
      <UserControl.Resources>
        <local:EntityCollectionValueConverter x:Key="EntityCollectionValueConverter" />
        
        <sdk:HierarchicalDataTemplate x:Key="ParcelTemplate"
                  ItemsSource="{Binding 
                Converter={StaticResource EntityCollectionValueConverter}, 
                ConverterParameter=Parcels}">
          <StackPanel Orientation="Horizontal" Width="300">
            <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
            <TextBlock Text="{Binding Path=AccountNumber, Mode=TwoWay}" 
                        Margin="5,0" Width="100" TextWrapping="Wrap" />
          </StackPanel>
        </sdk:HierarchicalDataTemplate>
        
        <sdk:HierarchicalDataTemplate x:Key="CountyTemplate"
                  ItemsSource="{Binding 
                Converter={StaticResource EntityCollectionValueConverter}, 
                ConverterParameter=Counties}"
                ItemTemplate="{StaticResource ParcelTemplate}">
            <StackPanel Orientation="Horizontal" Width="300">
              <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
              <TextBlock Text="{Binding Path=Name, Mode=TwoWay}" 
                        Margin="5,0" Width="100" TextWrapping="Wrap" />
            </StackPanel>
          </sdk:HierarchicalDataTemplate>
      </UserControl.Resources>
    
      <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel Orientation="Horizontal">
          <sdk:TreeView Name="treeViewControl" ItemsSource="{Binding Screen.Countries}" Width="400" >
            <sdk:TreeView.ItemTemplate>
    
              <sdk:HierarchicalDataTemplate 
                  ItemsSource="{Binding 
                Converter={StaticResource EntityCollectionValueConverter}, 
                ConverterParameter=States}"
                ItemTemplate="{StaticResource AssessorTemplate}">
    
                <StackPanel Orientation="Horizontal" Width="300">
                  <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
                  <TextBlock Text="{Binding Path=Name, Mode=TwoWay}" 
                        Margin="5,0" Width="100" TextWrapping="Wrap" />
                </StackPanel>
    
              </sdk:HierarchicalDataTemplate>
            </sdk:TreeView.ItemTemplate>
          </sdk:TreeView>
        </StackPanel>
      </Grid>
    </UserControl>

     

    Tuesday, August 23, 2011 5:51 PM
  • in Parcels the name is in "AccountNumbe"

    But in Counties and States you have it set to just "Name", is that correct?

    otherwise I would just try to get only one nexted collection working at a time.


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com

    Tuesday, August 23, 2011 7:16 PM
  • The item displayed in the Textblock:

    country level: Name

    State level: Name

    county level: Name

    parcel level: AccountNumber

     

    I did try it using country and state only first.  all the state level items produced that error.  Then I added the country level.  The error no longer occurred at the state level but now always occurred at the County level.  Then just to see what would happen I added the parcel level and the error no longer occurred at the state or the county level but now occurred only at the parcel level.  I guess I should play with it purely at the country and state levels for awhile to see what I can figure out.  I was hoping that the error was something one of you had come across before and know what caused it!

    But there is also another problem.  With 3 levels, the Name field displays fine (although the last level always gets that error message).  but when I add the fourth level (parcel) the items at the 3rd and 4th levels display as blank although the checkbox is there and works.  Is there some requirement that the textblock field at all levels be the same?

    Thanks for your help.

    Tuesday, August 23, 2011 10:20 PM
  • Okay.  I have finally figured it out!  The Xaml for the treeview control for the situation of each level of hierarchical data being in a separate table was set up wrong.  I remember reading about this during my research over the past couple of weeks and thought in the back of my mind somewhere that the Xaml code did not look quite right.  The key is that in each hierarchicaldatatemplate spec the ItemsSource and the ItemTemplate refer to the NEXT level NOT the current level.  The stackpanel and the textblock are specifying how that data should be displayed for the CURRENT level.  So I had to add another hierarchicaldatatemplate to my resources and give it the name StateTemplate and adjust the references to the various tables accordingly.  And the last or 4th level has no ItemsSource or ItemTemplate because it is the last level and nothing follows it.

    This clears both the problem with the error messages on the last level and the blank items at the lower levels. (I also found a misspelling in one of the fields)

    Here is the revised Xaml:

    <UserControl x:Class="SilverlightProject.SilverlightTracsTreeControl"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:local="clr-namespace:SilverlightProject"  
      xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="500">
    
      <UserControl.Resources>
        <local:EntityCollectionValueConverter x:Key="EntityCollectionValueConverter" />
        
        <sdk:HierarchicalDataTemplate x:Key="ParcelTemplate">
          <StackPanel Orientation="Horizontal" Width="300">
            <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
            <TextBlock Text="{Binding Path=AccoutNumber, Mode=TwoWay}" 
                        Margin="5,0" Width="100" TextWrapping="Wrap" />
          </StackPanel>
        </sdk:HierarchicalDataTemplate>
        
        <sdk:HierarchicalDataTemplate x:Key="AssessorTemplate"
                  ItemsSource="{Binding 
                Converter={StaticResource EntityCollectionValueConverter}, 
                ConverterParameter=Parcels}"
                ItemTemplate="{StaticResource ParcelTemplate}">
            <StackPanel Orientation="Horizontal" Width="300">
              <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
              <TextBlock Text="{Binding Path=Name, Mode=TwoWay}" 
                        Margin="5,0" Width="100" TextWrapping="Wrap" />
            </StackPanel>
          </sdk:HierarchicalDataTemplate>
    
    
        <sdk:HierarchicalDataTemplate x:Key="StateTemplate"
                  ItemsSource="{Binding 
                Converter={StaticResource EntityCollectionValueConverter}, 
                ConverterParameter=Assessors}"
                ItemTemplate="{StaticResource AssessorTemplate}">
          <!-- how to display state items -->
          <StackPanel Orientation="Horizontal" Width="300">
            <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
            <TextBlock Text="{Binding Path=Name, Mode=TwoWay}" 
                        Margin="5,0" Width="100" TextWrapping="Wrap" />
          </StackPanel>
        </sdk:HierarchicalDataTemplate>
      </UserControl.Resources>
    
      <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel Orientation="Horizontal">
          <sdk:TreeView Name="treeViewControl" ItemsSource="{Binding Screen.Countries}" Width="400" >
            <sdk:TreeView.ItemTemplate>
              <!-- Specify source and template for *next* level, i.e. state -->
              <sdk:HierarchicalDataTemplate 
                  ItemsSource="{Binding 
                Converter={StaticResource EntityCollectionValueConverter}, 
                ConverterParameter=States}"
                ItemTemplate="{StaticResource StateTemplate}">
                
              <!-- Specify how *top* level, i.e. country, is displayed -->
                <StackPanel Orientation="Horizontal" Width="300">
                  <CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
                  <TextBlock Text="{Binding Name, Mode=TwoWay}" 
                        Margin="5,0" Width="100" TextWrapping="Wrap" />
                </StackPanel>
    
              </sdk:HierarchicalDataTemplate>
            </sdk:TreeView.ItemTemplate>
          </sdk:TreeView>
        </StackPanel>
      </Grid>
    </UserControl>

     

    Thanks, everyone!

     

    Wednesday, August 24, 2011 12:33 AM
  • Wednesday, August 24, 2011 1:26 AM
  • For those of you that might be following this thread on treeview controls in LS but would like the initial state of the treeview to have all nodes expanded just add the following little nugget to your treeview Xaml resources section: (seems to work with both self ref table and multi-table tree views).
     
        <Style TargetType="sdk:TreeViewItem">
          <Setter Property="IsExpanded" Value="True" />
        </Style>
    
    Wednesday, August 24, 2011 6:29 PM
  • Hi,

    Thanks for some great reading material and guidance on building a hierarchical treeview control for LightSwitch. I'm having some problems adapting this material into a demo application for one of my customers.

    I'm getting an error on 

    IEntityCollection eCollection = 
                        entity.Details.Properties[sourcePropertyName].Value as IEntityCollection;
    


    where I'm recieving an error: Invalid argument 'name' (an ArgumentException).

    From my understanding this goes back to the XAML: 

    <sdk:HierarchicalDataTemplate 
                            ItemsSource="{Binding 
                        Converter={StaticResource EntityCollectionValueConverter}, 
                        ConverterParameter=Dim_Avdelings}">
    


    Dim_Avdelings is currently the plural name in LightSwitch for the datasource which I'm trying to build the tree on. It's a one table design like this (adapted from an existing system):

    Can anybody clue me in on what my error is? Please let me know if you need more information in order to understand the problem.

     

    Monday, September 05, 2011 8:41 AM
  • It should work if you try

    ConverterParameter=Dim_Avdeling
    


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com

    Monday, September 05, 2011 12:52 PM
  • I renamed Dim_Avdeling to Unit, in order to make it easier to understand in english. 

    I get the same error whether i try to set ConverterParameter=Unit or ConverterParameter=Units.

    It's always the same:  Invalid argument 'name'


    Monday, September 05, 2011 2:43 PM
  • I think the name that matters is what appears on the left-hand side of the screen designer that the control is on.

    Right now you are only showing us the table, not the screen the table is on.


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com

    Monday, September 05, 2011 3:07 PM
  • I found out what the error was, and it was a major brain freeze on my part. I used Units/Unit as ConverterParameter where it was supposed to be Subunits. I used the pluralized table name in stead of the Unit Collection property. Thanks for your help :)
    Tuesday, September 06, 2011 8:30 AM
  • How to communicate between the Tree an for example a grid on the LS screen?

    I like to select a tree item an position that record in a datagrid. How do i do that?

    Tuesday, September 06, 2011 4:44 PM
  • Rients,

    A detail discussion of this is in the general questions section of this forum under: List and Details screen with a custom control.  (Sorry, I don't know off hand how to reference a different post.)

    That was my question too as soon as I got the treeview itself working.  Basically you have to bind the SelectedItem of the treeview to the SelectedItem of the grid or control in LS.  The referenced thread goes into detail on this.

    Good luck!

    Tuesday, September 06, 2011 7:15 PM
  • How to adapt this to the treeview? As far as I can see there is no property on the TreeView called SelectedItem?

    I have a TreeView in left column and a standard input form on the right column that I want to change based on selections in the TreeView.

    Wednesday, September 07, 2011 9:23 AM
  • Probably depends on which treeview control you are using although I would suspect most of these controls have such a property.  I started off using the MS Silverlight treeview and will probably try to go back to it.  I am currently testing out the Telerik version which actually seems to have more features (like lines, built-in checkboxes, etc) but which also seems slower to me.  Anyway, previously in this thread I posted my Xaml code which details how to set up the MS Silverlight control.  In the other thread I posted a copy of my Xaml for the Telerik control which shows how I set up the SelectedItem property.  Note that the selecteditem clause goes in the Treeview control itself not in the hierarchicaldataitem or any other associated item.  I checked MSDN just now and see that the Selecteditem property for the MS Treeview control is readonly which I believe means you can bind for one-way use only.  It says to use the IsSelected property to set the selecteditem; this is also illustrated previously in this thread.
    Wednesday, September 07, 2011 3:08 PM
  • I have one way communication frm the Tree to the Grid. But from the Grid to the Tree give's the ReadOnly message.
    How do I add this, if possible?

    <Grid x:Name="LayoutRoot" Background="White">
      <StackPanel Orientation="Horizontal">
        <sdk:TreeView Name="treeViewControl" ItemsSource="{Binding Screen.HoofdOrganisaties}"
                     
    BorderBrush="#FFADA7A7" Background="LightGoldenrodYellow"
                     
    SelectedItem="{Binding Screen.Organisaties.SelectedItem, Mode=TwoWay}">
          
    <sdk:TreeView.ItemTemplate>
           
    <sdk:HierarchicalDataTemplate
                       
    ItemsSource="{Binding Converter={StaticResource EntityCollectionValueConverter},
                        ConverterParameter=Organisaties}">
             
    <StackPanel Orientation="Horizontal">
               
    <TextBlock Text="{Binding Path=Naam, Mode=TwoWay}" Margin="2,0" Width="100" />
              
    </StackPanel>
           
    </sdk:HierarchicalDataTemplate>
         
    </sdk:TreeView.ItemTemplate>
       
    </sdk:TreeView>
     
    </StackPanel>
    </Grid>

    Thursday, September 08, 2011 12:23 AM
  • Rients, are you sure this is right?

    SelectedItem="{Binding Screen.Organisaties.SelectedItem, Mode=TwoWay}">

    You are using "Screen.HoofdOrganisaties" as the ItemsSource two lines above that.. And what is the "ReadOnly" message, exactly, and when does it happen?

    Monday, September 12, 2011 12:21 AM
  • Michael,

    Why do you need an IsRootNode property in the entity? Why can't you set the filter to return only nodes whose ParentCategory is null. Before you tell me you can't do that, I know, I just tried it! What I want to know is why we can't do that? Entity Framework allows you to write a query where you check if a property is null, why can't Lightswitch? That would remove the need for this superfluous property.

    Thanks for another great article.


    If you're really bored, you could read about my experiments with .NET and some of Microsoft's newer technologies at http://dotnetwhatnot.pixata.co.uk/
    Monday, September 12, 2011 6:26 PM
  • It's a log story that has to do with the way the tre control calls the default constructor in the WCF RIA Service...

    Long story short is that Sheel Shah wrote code that gets past all issues. He is in the process of cleaning up the code and publishing on it.

     


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com

    Monday, September 12, 2011 6:38 PM
  • OK, just wondered. I haven't examined Sheel's code carefully, I just copied it in to get the sample working. Next step is to examine it and see how it works.

    Do you know if you can use a tree view instead of a grid for a master-details screen? I have a screen that handles categories, which are hierarchical like yours, but I would like the tree view on the left to show all the categories, and a details section on the right to show details of the currently selected category. I've been fiddling with the sample, but can't get it to work.

    Any ideas? Thanks again.


    If you're really bored, you could read about my experiments with .NET and some of Microsoft's newer technologies at http://dotnetwhatnot.pixata.co.uk/
    Monday, September 12, 2011 6:48 PM
  • The Sheel Shah code I am talking about has not been published yet.

    Sorry I have no examples on the other stuff.


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com

    Monday, September 12, 2011 6:56 PM
  • Sorry, I thought you meant the code for the converter, which I think was written by Sheel.

    I'll look forward to the next instalment then!


    If you're really bored, you could read about my experiments with .NET and some of Microsoft's newer technologies at http://dotnetwhatnot.pixata.co.uk/
    Monday, September 12, 2011 7:55 PM
  • Hi Karol,

    with your sample code I have write two kinds of treeview custom control, first one to lookup and second one to manage a big data tree view.

    I share here pictures and source code.

    Thanks a lot,

    daniel.

     

    Sunday, September 18, 2011 3:17 PM
  • Hi Karol,

    with your sample code I have write two kinds of treeview custom control, first one to lookup and second one to manage a big data tree view.

    I share here pictures and source code.

    Thanks a lot,

    daniel.

     


    That is nice how you use a "Value Converter" so you don't need the IsRootNode property that I have in my solution.

    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com

    Sunday, September 18, 2011 3:38 PM
  •  

    Hi Micheal,

    (thanks a lot about yout post on my blog)

    The big question, is there a way to do treeview lookup code 'entity' independent?  As you saw in the code, I've configured several values:

     

             Private strNomQuery As String = "ElementsDeCostArrel"
    
             Private strNomEntity As String = "dimElementDeCost"
    
             Private strNomCollecioChildren As String = "dimElementsDeCostChildren"
    
             Private strNomEntityParent As String = "dimElementDeCostParent"
    

    But some others do not know how to parameterize it​​:

                 TreeSelectedItem Dim As Microsoft.LightSwitch.Framework.Client.VisualCollection (OfLightSwitchApplication.dimElementDeCost) =
    
                     TryCast (Screen.Details.Properties (strNomQuery). Value, Microsoft.LightSwitch.Framework.Client.VisualCollection(Of LightSwitchApplication.dimElementDeCost))
    
                 treeSelectedItem.SelectedItem = SelectedItem
    

    or

     

             <sdk: TreeView Name = "TreeViewTaula"
    
                     Width = "700"
    
                            Height = "270"
    
                       ItemsSource = "{Binding Path = Screen.ElementsDeCostArrel, Converter = {StaticResource rootConverter}}"
    
                         ItemTemplate = "{StaticResource NameTemplate}">
    
             </ sdk: TreeView>
    
             Path=Value, Text="{Binding <TextBox Mode=TwoWay}"/> Name="txtBox"
    

    Do you think I can get  a 'generic' custom control component ? I know I'm close to achieve this, I have 3 hierarchical entities and code differs on few lines from one to another. 

     

    When I select a Combo I can change specific parameters like 'Choices'. With tree view specific parameters may be 'root nodes query', children property, ...

     

    bests regards.

     


    • Edited by danihp Sunday, September 18, 2011 5:09 PM
    Sunday, September 18, 2011 5:08 PM
  • The LightSwitch team is working on code that will address all these issues. I am afraid we must be patient. However I have seen the code and it is not 'vaperware'. They just want to release something that is tested ect.

    I Know I know we want it now :)


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com

    Sunday, September 18, 2011 5:36 PM
  • Any idea when we might see it? Is this something slated for v2, or would we be likely to get an intermediate update, like a service pack that would add the extras they've been doing since the release?

    Thanks


    If you're really bored, you could read about my experiments with .NET and some of Microsoft's newer technologies at http://dotnetwhatnot.pixata.co.uk/
    Sunday, September 18, 2011 7:26 PM
  • Any idea when we might see it? Is this something slated for v2, or would we be likely to get an intermediate update, like a service pack that would add the extras they've been doing since the release?

    Thanks


    If you're really bored, you could read about my experiments with .NET and some of Microsoft's newer technologies at http://dotnetwhatnot.pixata.co.uk/


    No this is just a normal Lightswitch Silverlight Custom Control.

    I could never talk about V2 stuff even if I knew :)

    I can confirm the code exists and it does work. However, I did not write it and I have no control over when it will be released. I cannot share any of the code because it is not my code to share.

    However, I don't want anyone to think that LightSwitch cannot do it.

     


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com

    Sunday, September 18, 2011 7:34 PM
  • Hey Folks,

    I've been working on the control that Michael is referring it.  This is not an official Microsoft or LightSwitch control.  Its a sample that I'm working on.  This will behave as a control extension for LightSwitch (you'll be able to pick it as a control in the screen designer when you have a collection selected). 

    The control will give you the following capabilities

    - Will display either a list of checkboxes or a tree of checkboxes for a many-to-many mapping table

    - It will let you customize the query that is used to determine the list of checkboxes (the choices)

    My current plan is to release the extension this upcoming week.

    Thanks!

    Sunday, September 18, 2011 7:41 PM
  • OK, thanks for the clarification.
    If you're really bored, you could read about my experiments with .NET and some of Microsoft's newer technologies at http://dotnetwhatnot.pixata.co.uk/
    Sunday, September 18, 2011 7:53 PM
  • Excellent Thread.  I've been able to successfully display hierarchical self referencing entities following Michaels excellent tutorial.  I'm looking forward to Sheel's upcoming extension treeview!

    However, when I add a new entity to the root collection generated from the query or to the underlying full entity set, it immediately shows up in the root collection.  If I refresh or load the root collection, it also shows up as a child, but continues to show up in the root.  The only way I've been able to have the treeview display the hierarchy correctly after adding a new entity is to save the collection and then refresh.  It's as if the query is not being executed unless the underlying datastore is changed.

      Is there a way to execute the query against the in-memory collection so that the user maintains control of when changes to their data are saved or discarded?

    Also, any word on the availability of Sheel's treeview?

    Thanks!

     

    Saturday, October 01, 2011 10:03 PM
  • That sounds very cool Sheel!

    Yann

    (plus ça change, plus c'est la même chose!)

    If you found this post helpful, please "Vote as Helpful". If it actually answered your question, remember to "Mark as Answer".

    This will help people find the answers that they're looking for more quickly.

    Sunday, October 02, 2011 12:45 AM
  • Dave, LightSwitch does not support querying against in-memory collections of entities.

    The reason you are seeing new entities at root level is that the root uses LightSwitch screen member (collection) directly and those always include new instances of corresponding entity type. But to overcome this you can apply the same binding converter mechanism to the root as you do apply to children. The purpose of the root converter (slightly different from the child converter) would be to filter out new entities. It should be really easy to modify Michael's tutorial  to achieve this: just do not add all entities to the final collection, but only those that satisfy the condition entiy.Details.EntityState != EntityState.Added.

    Hope that helps! Karol

    • Proposed as answer by Dave VB Saturday, October 08, 2011 8:53 PM
    Monday, October 03, 2011 2:01 AM
  • Nice!

    Yann

    (plus ça change, plus c'est la même chose!)

    If you found this post helpful, please "Vote as Helpful". If it actually answered your question, remember to "Mark as Answer".

    This will help people find the answers that they're looking for more quickly.

    Monday, October 03, 2011 5:59 AM
  • Karol,

    Thanks for your suggestion...seems like it ought to work.  In trying to follow the suggestion, I ran into the issue described in the thread: http://lightswitchhelpwebsite.com/Forum/tabid/63/aft/239/Default.aspx

    In addition to there being no documentation on the VisualCollection type mentioned in that thread, the collection received in the converter on loading of the screen has 0 elements.

    Do you have any examples of using a value converter to populate a collection in the screen data view model?

    Thanks - Dave

    Edit:

    After quite a bit of trial and error I figured out what I was doing wrong. In my custom control, I was binding the converter to the "Value" and then specifying the actual DataContext in the screen designer. Once I changed the custom control to point directly at my screen member (Screen.RootElementTypes), things worked perfectly.

     

            <my:TreeviewExt x:Name="treeViewControl" ItemsSource="{Binding Path=Screen.RootElementTypes, Converter={StaticResource RootEntityCollectionValueConverter}}" 
                                SelectedItem="{Binding Value.SelectedItem,Mode=TwoWay}" 
                                ItemTemplate="{StaticResource myChildrenTemplate}">
                </my:TreeviewExt>
    
    • Edited by Dave VB Saturday, October 08, 2011 8:52 PM
    • Proposed as answer by Dave VB Saturday, October 08, 2011 8:53 PM
    Tuesday, October 04, 2011 8:25 PM
  • Sorry it took me so long, but I've released my many-to-many tree view control. You can grab it here. Please let me know if you have any questions. http://code.msdn.microsoft.com/silverlight/Many-to-Many-Control-for-52cd8c6c
    • Edited by Sheel Shah Tuesday, January 17, 2012 5:15 AM
    Tuesday, January 17, 2012 5:10 AM
  • Sorry it took me so long, but I've released my many-to-many tree view control. You can grab it here. Please let me know if you have any questions. http://code.msdn.microsoft.com/silverlight/Many-to-Many-Control-for-52cd8c6c

    Hi Sheel,

    Thanks a lot!  I can't wait trying it out. You can't imagine how much a decent tree control is a top wanted feature. Every business app needs this.

    Take care

    -paul.

     


    paul van bladel
    Tuesday, January 17, 2012 6:25 AM
  • Hi Sheel,

    I tried the extension in a small demo project and in a few minutes it was up and running. 

    Very useful ! Thanks a lot.

    Nonetheless, I was a bit confused by the the title of this forum post (=treeview).  Your example is of course closer to a generic way to handle many to many selection, rather than a full treeview. 

    In fact, I'm searching for a straightforward solution to handle treeviews where the underlying data have a self-referencing structure (e.g. an employee table, with a nullable Manager field (for the top manager) which refers to another employee).

    Your excellent many-2-many solution has also self-referencing capabilities, but I'm looking for a full counter-part of a grid, i.e. a tree control where all fields of the current row can be viewed/edited. So, in terms of the example you suggest on the download page: a way to view/edit the blogpost categories in a treeview.

    What is in your view, currently the best solution for this in LightSwitch ?

    thanks

    paul.


    paul van bladel

    Tuesday, January 17, 2012 6:49 AM
  • Hi Michael,

    Thanks for the update.

    I know, but I have the feeling that this tree control can only used in combination with a many-2-many structure?

    I would like to have a simple tree control that simply makes a representation of a stand-alone self-referencing table.

    take care

    paul.


    paul van bladel
    Tuesday, January 17, 2012 10:54 AM
  • Hi everybody,

    I have published  a sample project with treeview custom control. Project covers CRUD+cut&paste operations also Lookups:

    http://youtu.be/xnbmnihVQcE

    Be free to get it at: 

    http://beutil.blogspot.com.es/2012/04/lightswitch-custom-control-tree-loojup.html




    • Edited by danihp Thursday, April 05, 2012 10:14 PM
    Thursday, April 05, 2012 9:42 PM
  • Hi everybody,

    I have published  a sample project with treeview custom control. Project covers CRUD+cut&paste operations also Lookups:

    http://youtu.be/xnbmnihVQcE

    Be free to get it at: 

    http://beutil.blogspot.com.es/2012/04/lightswitch-custom-control-tree-loojup.html




    This is great!

    Thanks!


    The Visual Studio LightSwitch Marketplace

    http://LightSwitchHelpWebsite.com

    Thursday, April 05, 2012 10:19 PM
  • Hi Michael,

    thanks about your comment. I share a new video. Treeview custom control managing a 2,5 Milions rows tree.

    http://youtu.be/9nPvesAYKn8

    I have wrote code ready to parametrize it, take a look to first lines of each file. It is really hard to convert this code to a new lightswitch control?

    regards,

    daniel.



    • Edited by danihp Saturday, April 07, 2012 6:51 PM
    Saturday, April 07, 2012 5:00 PM
  • I have write code ready to parametrize it, take a look to first lines of each file. It is really hard to convert this code to a new lightswitch control?

    regards,

    daniel.


    A collection control, like this control can be difficult.

    The Visual Studio LightSwitch Marketplace

    http://LightSwitchHelpWebsite.com

    Saturday, April 07, 2012 5:35 PM
  • It sounds like the grouping feature of FlexGrid for LightSwitch might be what some people need.  It's a grid, so you can databind, and you can enable grouping (it's an on/off property) for collapible nodes.  More info and demo at FlexGrid for LightSwitch
    Thursday, April 26, 2012 8:32 PM
  • Hi,

    Can you please explain how the component One grid has tree control functionality?

    Can it represent a self-referencing table (e.g. employee table with foreign key towards employee table) in a treeview?


    thx

    paul.


    paul van bladel


    Friday, April 27, 2012 6:22 AM
  • Hi,

    Is it possible to update a value with selecting item in tree view control ? 

    I mean I have a table that is self referenced and I have a second table that has reference to the Id of the first one.

    Now in Lightswitch I have edit screen that gets the list of items from the second table and for each row the last column should be this tree view with selected value from referenced Id, but when I Select other value and click save the referenced ID should change. 

    I am pretty new to Lightswitch.

    Monday, July 30, 2012 1:23 PM
  • Lukasz,

    I'm not 100% sure what you are trying to accomplish, but it sounds a lot like a Many-To-Many relationship situation.

    Check out the User's Guide for the Treeview control I wrote and see if that helps.  It discusses setting up the tables and the treeview to handle such relationships.

    http://visualstudiogallery.msdn.microsoft.com/ca292c74-661c-48ba-8262-d79a2671c33f

    If, on the other hand you are only trying to display a list of the items in the first table in each row of a datagrid of the second table and have a single item selected, you should be able to do that with standard LightSwitch controls.

    Dave

    Monday, July 30, 2012 6:47 PM
  • Hi Dave.

    I'll try to make it clear this time.

    This is just example 

    I have a table of cars. They are divided into hierarchy. The roots are for example (Sports cars, Normal Cars and Trucks), then each of them is divided into other categories. For example sports cars are divided into Formula 1, Dragsters, Drifters etc. and those are divided into named ones.

    Then I have a second table of drivers. And I assign driver to each car or car types from the hierarchy list.

    Now in lightswitch I have a edit screen that loads the drivers and in that screen I have a tree view of said cars. Now selecting a car from the list and saving updates the driver table with new car associated to that driver.

    Tuesday, July 31, 2012 6:08 AM
  • OK, I believe I understand what you are trying to do. 

    In LightSwitch, events are focused on the data.  If you select the collection that is the ItemsSource of your tree of cars, then select the dropdown for Write Code in the upper right of the designer screen, you will notice an event for SelectionChanged on your Car List in a group of Collection Methods.  Click on that and it will open a code window where you can code something like:

    Drivers.SelectedItem.Car = Cars.SelectedItem

    Then, each time the selected car changes, the Driver table will be updated.  When you press the Save button it will all be saved to the database or if the user wants to reset to the original values, they can press Refresh.

    Assuming you have the relationship between the Car and Driver table set up in LightSwitch, you do not need to manipulate the ID directly.  LightSwitch takes care of that as part of its Relationship management. 

    • Proposed as answer by DaveVanB Tuesday, July 31, 2012 11:02 AM
    • Unproposed as answer by DaveVanB Tuesday, July 31, 2012 11:03 AM
    Tuesday, July 31, 2012 11:02 AM
  • I did as you told but it didn't work. The SelectionChanged only executed on the start before the tree view control was populated with data and not when I went through tree view nodes.

    But I found a solution for my trouble. Mr Doron Goldberg wrote article for just what I needed.

    http://blogs.microsoft.co.il/blogs/dorong/archive/2011/11/14/lightswitch-and-silverlight-passing-parameters-to-a-screen.aspx

    Maybe someone might add this example to their tutorial lists.




    Tuesday, July 31, 2012 12:44 PM
  • If you are using the standard Silverlight TreeView control as a LightSwitch Custom Control, it will not change the SelectedItem in the collection because it is a ReadOnly property.

    I've been using my Treeview Extension control that has SelectedItem as a Read/Write property and it works like the native LightSwitch collection controls that will change the SelectedItem in the collection when the user changes their selection, making the task you are trying to accomplish much easier.

    Glad you found a solution.

    Tuesday, July 31, 2012 1:34 PM