Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Linq.GroupBy Key not binding in silverlight

list.ItemsSource=db.Templates.GroupBy(t=>t.CategoryName);

in xaml:

<DataTemplate>
   <TextBlock Text="{Binding Key}" />
</DataTemplate>

After this code. Don't show any text in TextBlock. I'm changing Text binding like this

<DataTemplate>
   <TextBlock Text="{Binding}" />
</DataTemplate>

TextBlock Text shown like this System.Linq.Lookup^2+Grouping[System.String,Model.Template]

I'm debugging and checking Key property. this is not null.

Why Key don't bind in TextBlock?

How to show group title in Textblock?

like image 434
ebattulga Avatar asked Dec 01 '11 14:12

ebattulga


2 Answers

Hmmm - unfortunate. The reason is because the result of the GroupBy() call is an instance of System.Linq.Lookup<,>.Grouping. Grouping is a nested class of the Lookup<,> class, however Grouping is marked as internal.

Security restrictions in Silverlight don't let you bind to properties defined on non-public types, even if those properties are declared in a public interface which the class implements. The fact that the object instance you are binding to is of a non-public concrete type means that you can only bind to public properties defined on any public base classes of that type.

You could build a public shim class to act as a view model for the grouping:

public class MyGrouping {
  public string Key {get; internal set;}
}

list.ItemsSource=db.Templates.GroupBy(t=>t.CategoryName)
                             .Select(g => new MyGrouping { Key = g.Key });
like image 114
RobSiklos Avatar answered Sep 21 '22 03:09

RobSiklos


It's been a while, but I had similar problem recently, so I decided to post another solution.

You can create a converter and return the value of Key from it

public class GroupNameToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var grouping = (IGrouping<string, [YOUR CLASS NAME]>) value;

            return grouping.Key;
        }

    }

and in Xaml you don't bind to Key, but to the grouping itself.

<TextBlock Text="{Binding Converter={StaticResource groupNameToStringConverter}}" />
like image 1
ekimpl Avatar answered Sep 19 '22 03:09

ekimpl